简体   繁体   English

使用node.js / express和AngularJS的CORS请求

[英]CORS requests with node.js/express and AngularJS

I would like to implement a very simple CORS scenario. 我想实现一个非常简单的CORS方案。 Here's my server written in node.js/express: 这是我用node.js / express编写的服务器:

var express        = require('express');
var morgan         = require('morgan');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var app            = express();
var router         = express.Router();

router.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Test-Header');
    next();
});

router.get('/', function(req, res, next) {
    console.log('Request arrived');
    res.json({data: 'hello'});
    next();
});

app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());  
app.use('/', router);

app.listen(app.get('port'), function(){
  console.log('Express is up on ' + app.get('port'));
});

To complement this I have a very simple AngularJS file as well: 为了补充这一点,我还有一个非常简单的AngularJS文件:

var app = angular.module('myapp', []);

    app.controller('MyCtrl', function($scope, $http) {
        var config = {
            headers:  {
                'X-Test-Header': 'Test Header Data'
            }
        };

        $scope.test = 'Hello World';
        $scope.getData = function () {
            console.log('clicked');
            $http.get('http://localhost:3000/', config).
            success(function (data, status) {
                console.log('Status: ', status);
                console.log('Data: ', data);
            }).
            error(function (data, status) {
                console.log('Status: ', status);
                console.log('Data: ', data || 'Request failed');
            });
        }
    });

The output in my console for the node/express app is simply: 在控制台中,node / express应用程序的输出很简单:

Express server listening on port 3000
OPTIONS / 200 4.767 ms - 3
Request arrived
GET / 200 2.572 ms - 16

And in the browser's console I see: 'clicked'. 在浏览器的控制台中,我看到:“单击”。

On the network tab I see that there were two request made once I have clicked the button - one OPTIONS that returned a 200 OK, and a GET method which is pending forever. 在“网络”选项卡上,单击按钮后我看到有两个请求-一个OPTIONS返回200 OK,另一个是GET方法,该方法永远待定。

网络标签

So my question is of course, why am I experiencing this behaviour? 所以我的问题当然是,为什么我会经历这种行为? I tried digging and read quite a few articles and tried their suggestions but none of them worked. 我尝试挖掘并阅读了许多文章,并尝试了他们的建议,但没有一个起作用。

Interestingly enough the following has fixed the issue: 有趣的是,以下内容解决了该问题:

router.all('/', function(req, res, next) {
    console.log('Request arrived');
    res.type('application/json');
    res.json({datax: 'hello'});
    next();
});

notice the diff --> router.get('/') vs router.all('/') . 注意router.get('/') > router.get('/') vs router.all('/') I'm a bit baffled why this is happening though. 我有点困惑为什么会这样。

UPDATE Here's a much better code that I put together, now that I understand this a bit more ... 更新这是我编写的更好的代码,现在我对此有了更多了解...

app.route('/')
    .options(function (req, res, next) {
        res.status(200).end();
        next();
    })
    .get(function (req, res) {
        res.json({data: 'hello'});
    });

And here's a quick writeup about my findings: http://tamas.io/node-jsexpress-cors-implementation/ 以下是关于我的发现的快速摘要: http : //tamas.io/node-jsexpress-cors-implementation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM