0

I've built a react + express app that makes requests on the client and server sides to an external API (the spotify API). My server and client are served on different ports (8888 and 3000). Requests on my server side are working fine and use the standard app.use("*", cors()) options to handle CORS, but axios requests on my client side create a CORS problem:

Access to XMLHttpRequest at "externalURL" 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.

My client side requests include an Auth token and headers:

 headers: {
        'Authorization': 'Bearer ' + authToken,
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
 }

I've tried reading some similar posts and the MDN docs on CORS but haven't been able to fix the problem.

  • The response from the external Spotify API endpoint is what needs to have Access-Control-Allow-Origin header — as a response header. But it doesn’t. And there are no changes you can make in your frontend JavaScript that can add a response header to a response from an external endpoint. The maintainers of the external endpoint would need to add the response header. – sideshowbarker Nov 25 '20 at 07:14
  • Thanks, I've enjoyed reading your posts on the subject across the site. Can I get around this with a proxy server, as some have suggested, and why was this not an issue when I ran the project locally vs. on heroku? – mijamessmith Nov 25 '20 at 19:47

1 Answers1

0

Try including this in ur server side

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,auth-token, Authorization,');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
Jackal
  • 493
  • 1
  • 5
  • 16
  • No luck, unfortunately. I tried to with and without the cors module. I'm wondering if because the react client is on a different port, 3000, these cors options on my server aren't applying? – mijamessmith Nov 25 '20 at 02:06
  • I don't think its related to the ports. try sending the request with and without the headers. – Jackal Nov 25 '20 at 02:15
  • The request requires an auth token and a content-type header regardless - otherwise I don't think CORS options would kick in and create this problem – mijamessmith Nov 25 '20 at 03:34