I\'m not able to correctly handle CORS issues when doing either PATCH
/POST
/PUT
requests from the browser sending an Authorization
I have pretty much similar issues with CORS and Vercel serverless function.
After lots of try → failed process I just found solutions for this.
The simplest solution, just using micro-cors.
And having an implementation something like;
import { NowRequest, NowResponse } from '@now/node';
import microCors from 'micro-cors';
const cors = microCors();
const handler = (request: NowRequest, response: NowResponse): NowResponse => {
if (request.method === 'OPTIONS') {
return response.status(200).send('ok');
}
// handle incoming request as usual
};
export default cors(handler);
using vercel.json
to handle request headers
vercel.json
{
"headers": [
{
"source": "/.*",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
},
{
"key": "Access-Control-Allow-Headers",
"value": "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"
},
{
"key": "Access-Control-Allow-Credentials",
"value": "true"
}
]
}
]
}
After self tried, there are 2 keys important in an above setting,
Access-Control-Allow-Origin
as what you wantAccess-Control-Allow-Headers
you must include Access-Control-Allow-Origin
into its value.then in serverless function, you still need to handle pre-flight request as well
/api/index.ts
const handler = (request: NowRequest, response: NowResponse): NowResponse => {
if (request.method === 'OPTIONS') {
return response.status(200).send('ok');
}
// handle incoming request as usual
};
I would suggest to read through the code in micro-cors, it's very simple code, you can understand what it'll do in under few minutes, which makes me didn't concern about adding this into my dependency.