【问题标题】:How to overcome CORS from Angular 2 to Node/express?如何克服从 Angular 2 到 Node/express 的 CORS?
【发布时间】:2017-09-10 11:48:21
【问题描述】:

我的快速应用程序中有此代码

var app = require('express')()
var bodyParser = require('body-parser')
var cors = require('cors')

app.use(bodyParser.urlencoded({ extended: true }))

app.post('/user', cors(), function (req, res) {
    res.send(req.body.username);
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

这是我发送请求的 angular 2 函数

getData() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    let params = 'username=test';

    this.http.post('http://localhost:3000/user', params, {headers: headers})
        .map(res => res.json())
        .subscribe(data => {});
}

我在控制台中收到此错误:

XMLHttpRequest 无法加载 http://localhost:3000/user。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。

但是当我使用 jquery ajax 发送请求时,它可以正常工作。

【问题讨论】:

    标签: jquery node.js ajax angular express


    【解决方案1】:

    您可以使用如下代码在 nodejs/express 中启用 CORS:

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
        res.header("Access-Control-Allow-Credentials", true);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
        next();
    });
    

    所以你的代码应该是这样的:

    var app = require('express')()
    var bodyParser = require('body-parser')
    
    app.use(bodyParser.urlencoded({ extended: true }))
    
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
        res.header("Access-Control-Allow-Credentials", true);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
        next();
    });
    
    app.post('/user', function (req, res) {
        res.send(req.body.username);
    })
    
    app.listen(3000, function () {
        console.log('Example app listening on port 3000!')
    })
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 2018-12-29
      • 2014-08-30
      • 2014-07-08
      • 1970-01-01
      • 2017-07-23
      • 2018-03-27
      • 2014-12-29
      • 1970-01-01
      相关资源
      最近更新 更多