繁体   English   中英

如何使用 JavaScript 调用 REST 服务?

[英]How to call REST service using JavaScript?

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

这是代码:

<!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 错误。

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

感谢大家的建议。

如果您需要发送数据,您需要将其作为查询参数或正文发送。 如果要将其作为正文发送,则需要使用 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,所以我使用了 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");

感谢大家的大力投入和帮助!

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

感谢这里对 SO 的所有了不起的帮助。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM