-1

I am trying to call an api but it is giving me following error :

Access to fetch at 'https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am using react and the code is :

try {
        let url = `https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01`;
        let response = await fetch(url,{
            mode: 'cors', // no-cors,
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
            "Accept": 'application/json',
            'Origin' : 'http://localhost:3000'
                //'Content-Type': 'text/xml'
                // 'Content-Type': 'application/x-www-form-urlencoded',
              },
        });

        this.setState(() => {
            return {
                searchResults : response
            }
        })
      } catch (error) {

        console.error(error);
      }

please guide what to do

Sadaf Sid
  • 1,510
  • 3
  • 17
  • 30

1 Answers1

1

The error is due to CORS, there is nothing wrong with the front-end code.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.

To fix this issue, the server should set the CORS headers, See here on how to enable CORS for your server

If your server is running express you need to set cors like this,

app.use(function(req, res, next) {
  // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); 
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

or use the cors middleware for express

Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33