如何解决向 Tomcat 发送 POST 请求时浏览器中的 Javascript 获取 API 错误?

How to resolve Javascript fetch API error in browser when sending POST request to Tomcat?

我在 Spring 启动中有一个 RESTful API,其中实现了一些端点。 Tomcat 运行 在端口 8080 上正常,Postman 请求得到响应,但我在尝试从浏览器获取时出错。

脚本:

  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 在 Postman 中请求:

localhost:8080/api/candy

与 body:

{
    "id": 243,
    "flavor": 2
}

returns:

{
    "id": 243,
    "flavor": 2
}

这是我所期望的。

访问localhost:8080时,Tomcat的欢迎页面可以正常打开,但不知道为什么不能发送POST请求。 Chrome 和 Opera 中的错误是:

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>

有什么想法吗?

编辑:在 Opera 下我得到了 Fetch API cannot load localhost:8080/api/candy. URL scheme must be "http" or "https" for CORS request. 错误,但可能是同一件事。

fetch()的第一个参数应该是请求资源的URL。您只使用缺少方案的 localhost:8080/api/candy

使用:

http://localhost:8080/api/candy

相反。

现在大多数工具(浏览器,邮递员),不显示当前页面的方案,但它仍然是必需的。