Ad

How To Resolve Javascript Fetch API Error In Browser When Sending POST Request To Tomcat?

- 1 answer

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.

Ad

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.

Ad
source: stackoverflow.com
Ad