如何启用不在vercel上工作的CORS



我已经用nodeJS和Express 构建了api服务器

然后我用CORS 软件包启用了CORS

import cors from "cors";
const app = express();
app.use(
cors({
origin: "*",
})
);

Vercel配置:

{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "./index.js"
}
]
}

然而,当访问vercel上的API服务器时,我总是会出现CORS错误。

Access to XMLHttpRequest at 'https://apiurl/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在本地测试设置启用CORS。上面的代码段有问题。

请告诉我这里出了什么问题。

谢谢

我知道我在回复一个很旧的帖子,但我刚刚和这个问题斗争了两天的大部分时间,所以如果其他人发现了这个问题,我希望它能有所帮助。。对我来说,解决问题的是vercel.json中的以下内容:

更改自:

{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "./index.js"
}
]
}

收件人:

{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "./index.js",
"methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
"headers": {
"Access-Control-Allow-Origin": "*"
}
}
]
}

事实证明,vercel会覆盖您放置在json之外的cors设置。不可能在同一个文件中混合使用头数组和路由数组。但是你可以在路线里面放一个标题。不要忘记方法,尤其是选项,因为它显然将许多请求转换为选项请求。

头必须是它自己的键,用于指定访问控制允许原点和"路线";将需要用";重写";因为标题键和路由键不在一起。如果您的应用程序有几个不同的域,则需要在每个域的外部标头数组中复制标头对象,以解决访问控制源问题。https://vercel.com/docs/project-configuration例如:

{
"version": 2,
"builds": [
{
"src": "./index.py",
"use": "@vercel/python"
}
],
"rewrites": [
{ "source": "/(.*)", "destination": "src/app.js" }
],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Origin", "value": "*" }
]
},
{
"source": "/vercel_app_domain_name/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Origin", "value": "*" }
]
}  
]
}

将其添加到您的Vercel配置中:

{
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "value": "*" },
{ "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
]
}
]
}

相关内容

  • 没有找到相关文章

最新更新