I am running a local REST API in Spring, the one at https://spring.io/guides/gs/rest-service/, written in Java. It works very when when I query it from my browser. This is:
http://<AWS IP>:8080/greeting
happily returns
{"id":3,"content":"Hello, World!"}
in the browser.
Good. Now, I just want to call this REST API from a Javascript in a web page. That's all.
So, I created a local webpage in my AWS server, in the "public" folder, with this content:
<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>
As you see, this simple Javascript just changes the text in the "demo" field, for the result of the "content" field in the Javascript. Elementary.
When I load this page, and I click in the button, nothing changes. Looking at the console, I see the following error:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at UserAction (sera.html:12)
at HTMLButtonElement.onclick (sera.html:23)
I have figured out that the error happens because after the "send", I am trying to parse an empty string (xhttp.responseText is empty), because if I hack the parsing line with the content from the API, it works. I mean, if I write
var qq = JSON.parse ('{"id":3,"content":"Hello, World!"}');
It works. It writes "Hello, World!" in the web page.
So, why am I getting an empty string? Why is xhttp.responseText empty?
- It is not that it's not finding the page, as I am not getting a 404 in the console.
- It cannot be a CORS issue, as I am calling the web page in the same domain/application server.
Calling a local API shouldn't be this difficult!
Thanks for your help in advance.
Algo
` – Mario R. Jul 02 '18 at 18:15