我在我的后端文件中使用express js,我在其中设置了cors策略。但是在 vercel 中部署支持的文件后,我无法在客户端获取数据。它给出了一个 cors 错误,错误是
Access to XMLHttpRequest at 'https://richter-restaurant-server-alzami12-al-zamis-projects.vercel.app/reviews' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我也有错误
Access to XMLHttpRequest at 'https://richter-restaurant-server-alzami12-al-zamis-projects.vercel.app/jwt' from origin 'http://localhost:5173' 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.
这是代码
app.use(cors({
origin: 'http://localhost:5173'
}));
这些是我的项目的依赖项
"dependencies": {
"@stripe/agent-toolkit": "^0.2.0",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"firebase-admin": "^13.0.1",
"form-data": "^4.0.1",
"jsonwebtoken": "^9.0.2",
"mailgun.js": "^10.2.4",
"mongodb": "^6.12.0",
"nodemailer": "^6.9.16",
"stripe": "^17.5.0",
"uuid": "^11.0.3"
}
我已经注释掉了服务器代码中的所有console.log和client.connect。我正在将 jwt 令牌保存在本地存储中
我尝试了给定的凭据:后端为 true 和前端的 withCredentials true 但它不起作用
我不知道这个
cors
模块,但您通常不需要它,您可以并且需要设置适合请求来源的标头以允许 CORS。
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.header('origin') || req.headers.origin || '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', 'true');
next();
})
无论如何,由于请求不是来自
localhost:5173
而是来自常规域,我认为这是您的设置需要更新的地方,并且应该使用域来信任作为值,但正如我所说,我不不知道这个模块。