向tomcat发送post请求时,如何解决浏览器中的javascript获取api错误?

sqougxex  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(222)

我在spring boot中有一个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);
  });

以 Postman 方式将请求发送至:

localhost:8080/api/candy

附正文:

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

返回:

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

这正是我所期望的。
当我访问时,tomcat的欢迎页面打开得很好 localhost:8080 ,但我不知道为什么它不能发送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. 错误,但可能是同一件事。

dfty9e19

dfty9e191#

的第一个参数 fetch() 应该是请求的资源的url。你只需要 localhost:8080/api/candy ,而该公司缺乏该计划。
使用:

http://localhost:8080/api/candy

相反
现在的大多数工具(浏览器、 Postman )都不显示当前页面的方案,但它仍然是必需的。

相关问题