This is a strange problem and I tried to debug it through the day with no effect. I have written a REST API in Spring 4 and it seems to be working fine. I've tested the links with postman, they work fine and even when I test it on the browser it works fine. So my works like this, If a I make a call to,
http://localhost:9000/myapi/receivedMessags/myUserId
I get JSON of this form,
[{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"}]
Which is perfectly valid JSON data.
Now I try to consume this data using the fetch-API. This is my function,
export function fetchMessages(url) {
return fetch(url, { method: "get",
headers: {
"Content-type": "text/plain"
},
credentials: 'include',
mode: 'no-cors'})
.then((response) => {
return response.json();//A
})
.then((data) => {
//console.log("data: ", data);
// let messages = [];
// for (let i = 0; i < data.length; i++) {
// let message = new Message(data[i].senderId, data[i].receiverId, data[i].mediaId);
// messages.push(message);
// }
console.log(data);
//return messages;
})
.catch((error)=> {
console.log("Request failed: ", error);
});
}
This method fails to access the data. I fails with the error,
Request failed: SyntaxError: Unexpected end of input(…)
After a lot of debugging I figured out that there's nothing wrong with the syntax and it fails at line A where it tries to parse the response to json.
If I change that line to response.text() the syntax error goes away and I get blank, which means there's no data. My question is why am I not able to access the data, when I know my server code is working fine.
If it helps, here's the server code,
@RequestMapping(value = "/receivedMessages/{userId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity getReceivedMessages(@PathVariable("userId") String userId) {
List<Message> receivedList = null;
try {
receivedList = controller.getReceivedMessages(userId);
} catch (Exception e) {
}
return new ResponseEntity(receivedList, HttpStatus.OK);
}
Infact, I've tried to POST on the API as well(which works fine in POSTMAN) but fails using my front-end client. Any help highly appreciated.
localhost:3000, I'm runningmydomain.com:3000