Access-Control-Allow-Origin: *在React中做axios post时不工作



我试图发布一个对象到API。然而,我得到以下错误:

Access to XMLHttpRequest at 'https://ciboservis.herokuapp.com/api/v1/filial/adm' from origin 'http://localhost:3001' has been 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.

我已经阅读了其他问题,发现我需要包括Access-Control-Allow-Origin: *。下面是我的代码:

axios
.post("https://ciboservis.herokuapp.com/api/v1/filial/adm", {testName: 'foo'}, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));

但是,我仍然得到相同的错误

正如Pratik在评论中提到的,您需要从服务器端应用这些标头,服务器端托管在Heroku上。

或者出于开发目的,您可以安装chrome插件来绕过此问题,但长期和更好的解决方案是在服务器端添加此头

你可以试试这个插件- CORS旁路扩展