由于 CORS 错误,POST 请求在反应 axios 中被阻止 [英] POST request blocked in react axios due to CORS error
问题描述
我正在尝试向包含多部分数据的 API 发送 POST 请求.
I am trying to send a POST request to an API with multipart data.
我在 postman 中测试了 API,在 Postman 中一切正常.但是当我在 React 中调用 API 时,它给了我 CORS 错误.
I test the API in postman and everything works fine in Postman. But when I call the API in react, it gives me CORS error.
我交叉检查了 URL、标题和数据,对我来说似乎一切正常.我对同一主题进行了多个 Stack Overflow 问题,发现我需要将 allow-cross-origin 与标头一起传递.我在标题中添加了它,但无法解决我的问题.
I cross-checked the URL, Header, and Data, all seems OK for me. I go through multiple Stack Overflow question on the same topic and found that I need to pass allow-cross-origin along with the header. I added that in my header but didn't able to solve my problem.
我在控制台中得到的错误是:
The error which I got in the console is:
请求的资源上不存在Access-Control-Allow-Origin"标头
API 调用代码
import axios from 'axios';
const header = {
"userid":localStorage.getItem("userid"),
"token":localStorage.getItem("token"),
"Content-Type": "multipart/form-data",
"Access-Control-Allow-Origin": "*"
}
const URL="https://api.hello.com/dashboard/venue_updated";
export function updateVenue(data,name,venue_type,email, phone_no,callback, errorcallback){
console.log(header);
axios.post(URL,data,{
params:{
name,
venue_type,
email,
phone_no,
},
headers:header
})
.then(res => {
if(callback != null){
callback(res);
}
})
.catch(err => {
if(errorcallback != null){
errorcallback(err);
}
})
}
我曾经在我的组件中导入它并在 form-submit 方法上调用它.
I used to import this in my component and call it on the form-submit method.
推荐答案
在 React 中使用该标头的 axios 调用无法解决 CORS.服务器的响应必须有 "Access-Control-Allow-Origin": "*"
axios call with that header in React doesn't solve CORS.
Server's response must have "Access-Control-Allow-Origin": "*"
检查网络选项卡并查看服务器的响应.
check network tabs and see server's response.
这篇关于由于 CORS 错误,POST 请求在反应 axios 中被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!