使用JS创建POST请求



我想从我的网站发送一个POST请求到我的后端。但我得到以下错误:blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的代码
const response = await fetch("http://172.18.6.249:8090/test", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: `{
"Id": 78912,
"Customer": "Jason Sweet",
"Quantity": 1,
"Price": 18.00
}`,
});
response.json().then(data => {
console.log(data);
});

服务器目前没有使用任何类型的身份验证。

如何避免错误?

CORS策略是非常重要的,也是安全的一部分。
如果你想忽略CORS,那么你可以使用:mode: "no-cors">in fetch Api

如果此问题仍然存在,则在后端注册此CORS策略。因此,您无法从您的IP地址命中请求。

下面是前端代码示例:
const response = await fetch("http://172.18.6.249:8090/test", {
method: 'POST',
mode : "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: `{
"Id": 78912,
"Customer": "Jason Sweet",
"Quantity": 1,
"Price": 18.00
}`,
});
response.json().then(data => {
console.log(data);
}); 

最新更新