Ilja Ilja - 1 year ago 163
Javascript Question

CORS issue performing api calls in react/redux application

I was trying to implement a mailchimp api and came across a cross domain issue with an error in chrome like this:

XMLHttpRequest cannot load
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '' is therefore not allowed
access. The response had HTTP status code 501.

After some research it turns out that api calls I make are made from the browser (I simply call api from one of my actions), but to fix this issue they need to be made on the server.

Hence I am trying to figure out a way to call an api from the server inside of my action, to bypass this issue.

One of the solutions I found is to use jsonp for this, however I had to drop it as well, as I can't authenticate with it.

Answer Source

The solution I found is to proxy api calls through express in the following way:

In your express config:

import request from 'request'

app.use('/api', function (req, res) {
  let url = 'your_api_url' + req.url

What this allows you to do is instead of calling in your components is to use /api/endpoint this way express will replace all instances of /api on your server with your api url and perform an api call from the server itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download