我在Spring中运行的是本地REST API,位于https://spring.io/guides/gs/rest-service/,是用Java编写的。当我从浏览器中查询它时,它非常有用。这是:
http://<AWS IP>:8080/greeting
愉快地返回
{"id":3,"content":"Hello, World!"}
在浏览器中。
好。现在,我只想从网页中的Java语言调用此REST API。就是这样。
因此,我在AWS服务器的“ public”文件夹中创建了一个本地网页,内容如下:
<Html>
<head>
<script>
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "greeting?name=Pepito", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var qq = JSON.parse (xhttp.responseText);
document.getElementById("demo").innerHTML = qq.content;
}
</script>
<body>
<p id="demo">Algo</p>
<button type="button" onclick="UserAction()">Search</button>
</body>
</html>
如您所见,这个简单的Javascript只是更改了“ demo”字段中的文本,以获取Javascript中“ content”字段的结果。小学。
当我加载此页面并单击按钮时,没有任何变化。在控制台上,我看到以下错误:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at UserAction (sera.html:12)
at HTMLButtonElement.onclick (sera.html:23)
我发现发生错误是因为在“发送”之后,我试图解析一个空字符串(xhttp.responseText为空),因为如果我用来自API的内容破解了解析行,那么它将起作用。我的意思是,如果我写
var qq = JSON.parse ('{"id":3,"content":"Hello, World!"}');
有效。它写着“你好,世界!”在网页中。
那么,为什么我得到一个空字符串?为什么xhttp.responseText为空?
调用本地API并不难!
谢谢您的帮助。