Following is the serverless yml template to deploy my functions to aws. The following snippet shows the configuration for one of the endpoints,
functions:
publish:
handler: lambda.publish
events:
- http:
method: post
path: publish
cors:
origin: ${self:custom.origin.${self:custom.stage}}
allowCredentials: true
This is my fetch request,
fetch(`${SOME_DOMAIN}/publish`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
I am handling response headers in my lambda like this,
const ALLOWED_ORIGINS = [
'http://localhost:3001',
'https://staging.company.com.au',
'https://blaze-staging.company.com.au',
'https://www.company.com.au',
'https://blaze.company.com.au',
'https://direct.company.com.au',
]
const origin = event.headers.origin
let headers
if (ALLOWED_ORIGINS.includes(origin)) {
headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': true,
}
} else {
headers = {
'Access-Control-Allow-Origin': 'http://localhost:3001',
}
}
const response = {
statusCode: 200,
headers,
body: JSON.stringify({ message: 'Successfully published the message.' }),
}
callback(null, response)
I am not able to get the pre-flight requests to work as I cannot set multiple origins. How to get around this problem? setting mode: 'no-cors'
on the request is actually allowing requests from any domain. Any help is much appreciated.