如何使用JavaScript调用REST服务?

时间:2020-05-21 12:22:42

标签: javascript html rest

使用我从StackOverflow帖子之一中找到的代码,我试图调用REST服务GET方法。但是,当代码运行时,并没有在URL中正确放置GET格式。

这是代码:

<!DOCTYPE html>
<script>
    function UserAction(json)
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function ()
        {
            if (this.readyState == 4 && this.status == 200)
            {
                alert(this.responseText);
            }
        };
        xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.send(json);
    }

</script>

<form>
    <button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
    <label for="json">JSON:</label>
    <input type="text" id="json" name="json"><br><br>
</form>

</html>

此GET REST服务的预期格式为:

http://localhost:8080/isJsonValid/json

(其中上一行的json是作为参数发送的实际JSON。)

但是,URL行中显示的内容包括项目,目录,并且URL具有?name = value语法。

由于GET与简单的 http://localhost:8080/isJsonValid/json 格式不匹配,因此出现404错误。

我意识到我显然缺少一些东西。

感谢所有人的建议。

2 个答案:

答案 0 :(得分:0)

如果需要发送数据,则需要以查询参数或正文的形式发送。如果要将其作为正文发送,则需要使用POST类型。下面是POST类型的示例。

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function() {
 // Begin accessing JSON data here
  var data = JSON.parse(this.response)

  if (request.status >= 200 && request.status < 400) {
    data.forEach(movie => {
      console.log(movie.title)
    })
  } else {
    console.log('error')
  }
}

// Send request
request.send()

用于发帖请求。由于我没有任何API,因此我使用了get API URL。

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    console.log(this.responseText)
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");

答案 1 :(得分:0)

感谢大家的大力支持和帮助!

对我来说最好的解决方案是按照建议使用POST。 GET总是放“?”即使我将其连接在URL中,“?” REST服务无法解释GET参数,因此它不能那样工作。在我使用的REST框架中,GET参数只是与一个或多个“ /”作为URL中的分隔符连接在一起。

在此感谢所有出色的帮助。 :)

相关问题