I\'ve been struggling so long with the error below. I\'ve tried so many tutorials and stackoverflow answers and none of the solutions fixes my problem.
If Someone using serverless with nodejs and facing this issue of prelight with cors-policy, here is the simple solution ...
functions:
externalHandler:
handler: handler.handlerExport
events:
- http:
path: handlerPath
method: post
cors:
origin: '*' # <-- Specify allowed origin
headers: # <-- Specify allowed headers
- Content-Type
- X-Amz-Date
- Accept
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: false
inside the handler file
if you are using express
...
const app = express();
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"x-www-form-urlencoded, Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
next();
});
...
or in general
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
product: product
}),
};
for more information refer serverless article