How To Resolve Javascript Fetch API Error In Browser When Sending POST Request To Tomcat?
I have a RESTful API in Spring Boot with a few endpoints implemented. Tomcat is running fine on port 8080, and Postman requests get a response, but I get errors when trying to fetch from the browser.
The script:
let candy = {
id: id, //previously declared id variable being passed
flavor: 0
};
fetch('localhost:8080/api/candy', {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(candy)
})
.then(response => response.json())
.then((response) => {
console.log(response.message);
});
POST request in Postman to:
localhost:8080/api/candy
with body:
{
"id": 243,
"flavor": 2
}
returns:
{
"id": 243,
"flavor": 2
}
which is what I expect.
The welcome page from Tomcat opens just fine when I visit localhost:8080
, but I don't know why it can't send the POST request. The errors both in Chrome and Opera are:
GET http://localhost:8080/favicon.ico 404 //this one only under Chrome
Fetch API cannot load localhost:8080/api/candy. URL scheme "localhost" is not supported.
Uncaught (in promise) TypeError: Failed to fetch
at HTMLButtonElement.<anonymous>
Any ideas?
Edit: under Opera I get the
Fetch API cannot load localhost:8080/api/candy. URL scheme must be "http" or "https" for CORS request.
error, but it is probably the same thing.
Answer
The first parameter of fetch()
should be the URL of the requested resource. You use just localhost:8080/api/candy
, which lacks the scheme.
Use:
http://localhost:8080/api/candy
instead.
Most tools (browsers, postman) nowadays, don't show the scheme of the current page, but it is nevertheless required.
Related Questions
- → CORS header 'Access-Control-Allow-Origin' missing only in browser/jquery but OK with curl
- → How to use foreach in jstl + javascript?
- → Server-side rendering of Java, ReactJs code on a web browser
- → MySQL JDBC driver not found in Tomcat 7 on Ubuntu 14.04 LTS
- → ambiguous mapping while deploying
- → Programmatically get Tomcat8 HTTP Connector's maxPostSize in a JSP
- → Element type "Resource" must be followed by either attribute specifications, ">" or "/>"
- → Caching lookups on application startup doesn't work
- → getting too many follow-up request as response of request
- → Apache Tomcat configuration: Access not authorized
- → Tomcat: One or more listeners failed to start
- → How to keep running a program on Linux through SSH connection?
- → Eclipse closed automatically