首页 > 解决方案 > 带有Angular的Node.js - 我发送请求时出现CORS错误

问题描述

我的 node.js API 有问题。我在端口 3000 上运行 API,在端口 4200 上运行角度前端。

当我从 Angular 向 API 发送请求时,CORS 出现错误。我尝试了三种不同的解决方案,但仍然无法正常工作。

  1. 第一个解决方案是安装 cors 包,并添加到代码中

app.use(cors());

  1. 第二种解决方案是在下面添加代码:
 app.use((req, res, next) => {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
   next();
})
  1. 最后一个解决方案是在下面添加代码,带有前端 url:
app.use(cors({
  origin: 'http://frontend.com:4200'
}));

以上都不起作用,即我仍然一直收到 CORS 错误。当我从邮递员发送请求时,一切正常。

我的实际代码:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const carRoutes = require('./routes/car');
const sequelize = require('./util/db');
const cors = require('cors');

sequelize.sync().catch(error => {
  console.log(error);
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

app.use(carRoutes);
app.listen(3001);

错误信息:

对另一个来源的资源的请求已被阻止:“同源策略”策略不允许从“ http://localhost:3000/car ”加载远程资源(CORS 请求失败)。

标签: node.jsangular

解决方案


有时 CORS 不仅仅是 Access-Control-Allow-Origin。尝试以下操作:

// Set up CORS
app.use(cors({
    origin: true, // "true" will copy the domain of the request back
                  // to the reply. If you need more control than this
                  // use a function.

    credentials: true, // This MUST be "true" if your endpoint is
                       // authenticated via either a session cookie
                       // or Authorization header. Otherwise the
                       // browser will block the response.

    methods: 'POST,GET,PUT,OPTIONS,DELETE' // Make sure you're not blocking
                                           // pre-flight OPTIONS requests
}));

您也可以使用allowedHeadersexposedHeaders。设置maxAge将减少飞行前请求的数量 - 它并不能真正解决 cors 问题,但会减少网络流量。

请注意origin: true。如果您的端点需要凭据,则浏览器将不遵守该*模式。Access-Control-Allow-Origin 标头必须与请求的 url 匹配(包括天气是 http 或 https)。幸运的是cors,如果您设置origin为,中间件会自动为您执行此操作true


推荐阅读