Ilja Ilja - 5 months ago 55
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 https://us9.api.mailchimp.com/3.0/members.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example.com' 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.

EDIT:
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

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
  req.pipe(request(url)).pipe(res)
})

What this allows you to do is instead of calling https://myapi.com/endpoint 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.

Comments