Oleksii Antoshkin
Oleksii Antoshkin

Reputation: 159

How to prevent CORS policy to block requests from localhost to third party API?

I'm developing ReactJS application integrated with 3rd party API. I can successfully execute same requests with Postman, but they are being blocked when executing from React application in browser. I am aware about CORS and how to solve the problem when I refer my own backend, but in this case obvoiusly I cannot. I tried to do requests with several JS modules intended to do similar stuff, but got the same error for each.

Access to fetch at 'http://api.example.com/resource/request?param=value' 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.
import React, {Component} from 'react';
import fetch from 'fetch';
import request from 'request';

class App extends Component {
  render() {
    return (
        <div className="App">
          <button onClick={this.sendWithXmlHttpRequest}>send XMLHttpRequest
          </button>
          <button onClick={this.sendWithFetch}>send Fetch</button>
          <button onClick={this.sendWithRequest}>send Eequest</button>
        </div>
    );
  };

  sendWithXmlHttpRequest = () => {
    let req = new XMLHttpRequest();
    req.open('get', url, true);
    req.send();
  };

  sendWithFetch = () => {
    fetch.fetchUrl(url, (error, meta, body) => {
      console.log(error, meta, body);
    });
  };

  sendWithRequest = () => {
    request.get(url);
  };

}

const url = 'http://api.example.com/resource/request?param=value';

export default App;

Upvotes: 1

Views: 1252

Answers (2)

Sultan H.
Sultan H.

Reputation: 2938

This fixes the problem, but I don't think it's something you are willing to include in a Production Ready application.

  sendWithXmlHttpRequest = () => {
    // Added a Proxied server which works as a middle-man to fetch the data for you.
    const urlWithProxy = `https://cors-anywhere.herokuapp.com/${url}`
    let req = new XMLHttpRequest();
    req.open('get', url, true);
    req.send();
  };

This is from..

The preferrable way is just to have a server.js that serves your Bundled App and that may -odds are few- require some Request Policy, but, to my expectations it will be enough with no configuration since the request is going to be proxied via Node not React.

Upvotes: 1

Akhil Sharma
Akhil Sharma

Reputation: 355

Assuming you are using Node for your backend. From the server side send the Access-Control-Allow-Origin header as * so that the client knows about the server policy.You can add cors npm package to do the job for you aswell. Below is the code on how I solved this on the express side:

app.use(function(req, res, next) {
res.header(“Access-Control-Allow-Origin”, “*”);
res.header(“Access-Control-Allow-Methods”, “GET,PUT,POST,DELETE”);
res.header(
“Access-Control-Allow-Headers”,
“Origin, X-Requested-With, Content-Type, Accept”
);
next();
});
app.options(“*”, cors());

Additionally you can install some CORS extension on the browser and enable requests. One such extension https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc

Upvotes: 1

Related Questions