I'm using middy for handling middleware for my AWS lambda code. Below is my code:
const middy = require('middy')
const middlewares = require('middy/middlewares')
const handlerWrapper = (handler) => middy((event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
let code = 200
context.send = (body) => callback(null,{
statusCode: code,
body: JSON.stringify(body)
})
context.status = (_code) => {
code = _code
return context
}
return handler(event, context ,callback)
}).use(middlewares.jsonBodyParser()).use(middlewares.cors())
The problem is, my front-end is sending a custom header named authorizationv2
and when my front-end tried to send a request to my AWS lambda code, the browser will display this error
Access to XMLHttpRequest at 'https://apiv2.website.com/data/list/' from origin 'http://admin.website.com' has been blocked by CORS policy: Request header field authorizationv2 is not allowed by Access-Control-Allow-Headers in preflight response.
So I assume to fix this, I need middy
to allow custom header authorizationv2
. I'm not entirely sure how to do this using middy.
You need to add the custom header in the preflight response. Two ways to do it: