Hi, I’m having issue trying to get Netlify Lambda respond properly to CORS preflight requests.
Go to any site and do a fetch request like this and you’ll see the error
fetch('https://ravely-widget.netlify.app/api/actions/tester', { method: 'POST', body: JSON.stringify({a:'a'}), headers: { 'Content-Type': 'application/json' } }).then(res => res.text()).then(console.log).catch(console.log)
Within my lambda function I detect if the event.httpMethod
is OPTIONS
, if it is I return a response with CORS headers:
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': '*',
};
if (event.httpMethod === 'OPTIONS') {
console.log('OPTIONS ', { CORS_HEADERS });
return {
statusCode: 200,
headers: CORS_HEADERS,
body: JSON.stringify({ message: 'Successful preflight call.' }),
};
}
However when I do an OPTIONS request using Postman/Insomnia it does not return those headers, e.g.
making a POST request to http://ravely-widget.netlify.app/api/actions/tester
which causes the preflight requests done by browsers to fail (when it called from outside my domain).
This is all I get (notice the missing access-control-allow headers)
< HTTP/2 200
< cache-control: no-cache
< server: Netlify
< x-nf-request-id: 01FDD1DKW929G2BXB2XQBM7BB0
< age: 1
< date: Wed, 18 Aug 2021 16:27:30 GMT
< content-length: 0
It works properly on my local dev server — if I were to try the same on my local dev server I’d get this (access-control-allow- headers are present)
< HTTP/1.1 200 OK
< x-powered-by: Express
< access-control-allow-origin: *
< access-control-allow-headers: Content-Type
< access-control-allow-methods: *
< date: Wed, 18 Aug 2021 16:24:17 GMT
< connection: close
< transfer-encoding: chunked
Does anyone know how to solve this? Thanks!
Netlify site name: ravely-widget.netlify.app