5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pranay kumar
  • 1,983
  • 4
  • 22
  • 51

3 Answers3

4

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());
Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18
0

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.

c01d-br0th3r
  • 465
  • 1
  • 5
  • 11
-2

Go this URL code and Enable CORS settings if you have access to it. https://api.hello.com/dashboard/venue_updated

Rain.To
  • 504
  • 2
  • 7