我对 CORS 和 Vercel 无服务器功能有非常类似的问题。
经过很多尝试→失败过程我刚刚找到了解决方案。
解决方案
tldr
最简单的解决方案,只需使用微科尔斯 https://github.com/possibilities/micro-cors.
并有一个类似的实现;
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
处理请求标头
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"
}
]
}
]
}
自行尝试后,有2个关键重要在上述设置中,
- 您必须设置
Access-Control-Allow-Origin
如你所愿
- In
Access-Control-Allow-Headers
you 必须包括 Access-Control-Allow-Origin
成其价值。
那么在无服务器功能中,您仍然需要处理飞行前请求 https://developer.mozilla.org/en-US/docs/Glossary/Preflight_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
};
我建议阅读中的代码微科尔斯 https://github.com/possibilities/micro-cors,这是非常简单的代码,您可以在几分钟内理解它会做什么,这使我不关心将其添加到我的依赖项中。