Redirect CORS issue

We are testing a simple redirect from a function:

export const handler = async () => {
return {
statusCode: 302,
headers: { Location: “https://www.google.com/” ,
“Access-Control-Allow-Origin”:“*”,
“Access-Control-Allow-Credentials”: “true”,
“Access-Control-Allow-Methods”: “GET, OPTIONS, POST, PUT”,
“Access-Control-Allow-Headers”: “x-custom-header, Content-Type”,
“Vary”: “Origin”,
}
}
}


.toml file

[[redirects]]
from = “/.netlify/functions/*”
to = “https://p/.netlify/functions/hello-world/:splat”
status = 200

[[redirects]]
from = “/*”
to = “/index.html”
status = 200


Snippet of calling code:
fetchBtn.addEventListener(‘click’, async () => {
const response = await fetch(‘hello-world’, {headers: {
“Access-Control-Allow-Origin”: “*”,
“Access-Control-Allow-Headers”: “Content-Type”,
“Access-Control-Allow-Methods”: “GET, POST, PUT, DELETE”,
},})
.then(response => response.json()
)

      responseText.innerText = JSON.stringify(response)
    })

No matter what change we make to the calling code or add whatever headers we get the following issue.

Access to fetch at ‘https://www.google.com/’ (redirected from ‘/hello-world’) from origin ‘http://localhost:8888’ 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.

Hi @MaharashtraMandalDen, thanks for posting.

First of all just want to find out if the p in the domain is intentional or it’s a typo. if it’s a typo kindly fix it.

Finally instead of calling your function on the endpoint hello-world as indicated below…

Kindly call your function on the endpoint relative to the base URL of your site: /.netlify/functions/hello-world

Make the changes and let me know the outcome.
Thanks.

I simply did this instead and it worked

Sender code:
export const handler = async () => {
return {
statusCode: 302,
headers: { Location: “https://www.google.com/” ,
}}
}


Calling code:
fetchBtn.addEventListener(‘click’, async () => {
const response = await fetch(‘/.netlify/functions/hello-world’, {mode:‘no-cors’})
.then(response => response.text()
.catch(e => {
console.log(e);
return e;
})
)

And it worked!

2 Likes

Hi @MaharashtraMandalDen, glad to know you resolved the problem.