问题
I am trying to send a POST request to an API with multipart data.
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.
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:
No 'Access-Control-Allow-Origin' header is present on the requested resource
API Calling Code
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);
}
})
}
I used to import this in my component and call it on the form-submit method.
回答1:
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.
回答2:
you have to add in your backend like this . (This example for nodejs)
app.use(cors(), function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
for Enable All CORS Requests
app.use(cors());
回答3:
Go this URL code and Enable CORS settings if you have access to it. https://api.hello.com/dashboard/venue_updated
来源:https://stackoverflow.com/questions/62296194/post-request-blocked-in-react-axios-due-to-cors-error