Home
Support Forums

CORS error when calling netlify function on redirected site

I have a site https://tunes.emilybonar.com/ that I’ve redirected to https://www.emilybonar.com/TuneTester/. It has a Netlify function which calls the spotify API and returns data. When I access the website at tunes.emilybonar.com, it works fine. However, when I go to emilybonar.com/TuneTester, I get a CORS error. My function endpoint is https://tunes.emilybonar.com/.netlify/functions/getSpotifyData?id=${id}. How do I configure this so I don’t get errors?

You can try defining the following headers on your request if you’re not doing it already:

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'

I added it as such:

fetch(`http://tunes.emilybonar.com/.netlify/functions/getSpotifyData?id=${id}`,
                {
                    headers: {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Headers": "Content-Type",
                        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
                    },
                },
            )

And I still get the following errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://tunes.emilybonar.com/.netlify/functions/getSpotifyData?id=5xif4sULGuWiZDVCcjNXxR. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://tunes.emilybonar.com/.netlify/functions/getSpotifyData?id=5xif4sULGuWiZDVCcjNXxR. (Reason: CORS request did not succeed).

TypeError: NetworkError when attempting to fetch resource.

My bad, the headers should not be on request, but on response. I just read about it here: https://community.akamai.com/customers/s/article/Cross-Origin-Request-Blocked-The-Same-Origin-Policy-disallows-reading-the-remote-resource-at-URL

When Site X is loading any content from Site Y:

Quoted from there:

To fix this issue, Site Y has to send Access-Control-Allow-Origin: * response header to allow other site to load resources. In case you want to allow only site X, then site Y should send Access-Control-Allow-Origin: [http://](http:)<domain-of-site-x>> to browser.

This hopefully fixes it.

1 Like