NodeJS Vercel - 请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述 投票:0回答:1

我在 VERCEL 上托管了 2 个应用程序。

第一个是 Angular 17 应用程序。 第二个是 NodeJS Express 服务器。

我的 Angular 应用程序正在调用 NodeJS 应用程序的 API 路由,但我遇到了 CORS 问题:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试过的:

vercel.json

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

index.js

// index.js
const express = require('express');
const connectDB = require('./config/database');
const playersRouter = require('./routes/players');
var cors = require('cors')
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
  
connectDB();
// Routes
app.use('/api/players', playersRouter);

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

来自 Postman 的所有请求都工作正常,但来自我的 Angular 应用程序的每个请求都被 CORS 阻止...

angular.app.vercel.com -> 调用 -> nodejs.app.vercel.com/api/players?search=John = CORS 问题

邮递员 -> 呼叫 -> nodejs.app.vercel.com/api/players?search=John = 工作 + 无 CORS 问题

感谢您的帮助

node.js angular express cors vercel
1个回答
0
投票

您可以尝试删除目的地吗?标题似乎也是一个数组。

"routes": [
      {
         "src": "/(.*)",
          "methods": ["GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
          "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" },
      ]
     }
   ]
© www.soinside.com 2019 - 2024. All rights reserved.