带有Angular的Node.js-发送请求时出现CORS错误

时间:2019-06-27 20:44:45

标签: node.js angular

我的node.js API有问题。我的API在端口3000上运行,而前端在端口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. 最后的解决方法是在下面添加代码,并添加前端网址:
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请求失败)。

2 个答案:

答案 0 :(得分:0)

有时,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可以减少飞行前请求的数量-不能真正解决问题,但可以减少网络交通。

  

请注意origin: true。如果您的端点需要凭据,则浏览器将不遵守*模式。 Access-Control-Allow-Origin标头必须与请求的网址匹配(包括天气为http或https)。幸运的是,如果您将cors设置为origin

true中间件将自动为您完成此操作

答案 1 :(得分:-1)

一个更简单的解决方案是实现代理,该代理会将您的API调用重定向到localhost:300。 添加一个名为proxy.config.json的新文件,并在其中添加以下json配置。

{
    "/car/*": {
        "target": "http://localhost:3000", 
        "secure": false,
        "logLevel": "debug"
    }
}

此后,您需要使用以下代码更新package.json,以更新Scripts部分:"start": "ng serve --proxy-config proxy.config.json",。请在使用npm start时执行上述操作,否则,您可以仅在命令行中运行ng serve --proxy-config proxy.config.json而不更新package.json,但是您必须记住每次都运行它。