angular $ http请求从80端口到另一个端口

时间:2017-03-06 13:32:07

标签: angularjs node.js http cors cross-domain

我正在尝试使用$ http方法从角度1项目在本地服务器上使用端口3000命中节点api但是我收到此错误:

  

XMLHttpRequest无法加载http://localhost:3000/login。请求标头   Access-Control-Allow-Headers中不允许使用字段授权   飞行前响应。

我还在节点js中添加了Access-Control-Allow-Origin : *

req.on('end', function() {
    req.rawBody = req.rawBody.toString('utf8');
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', '*');
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', '*');
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    // res.setHeader('Access-Control-Allow-Credentials', false);
    next();
});

我的角度代码是:

var req = {
            method: 'POST',
            url: 'http://localhost:3000/login',
            headers: {
                'Content-Type': 'application/json',
                // 'cache-control': 'no-cache'
            },
            data: { username: username, password: password },
            json: true
        };

        $http(req).then(function successCallback(response){
            console.log(response);
        }, function errorCallback(response){
            console.log("Error : ");
            console.log(response);
        });

但我仍然收到此错误。

1 个答案:

答案 0 :(得分:2)

错误在指定的预检响应中。 所以你需要处理OPTIONS方法:

req.on('end', function() {
    req.rawBody = req.rawBody.toString('utf8');
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', '*');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', '*');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    // res.setHeader('Access-Control-Allow-Credentials', false);


    if (req.method === "OPTIONS") {
        return res.status(200).end();
    }

    return next();
});

这是由于浏览器处理跨源请求的方式。在POST之前发送OPTIONS请求(预检)以获取允许的起源,标题和方法。