【问题标题】:angular $http request from 80 port to another port从 80 端口到另一个端口的角度 $http 请求
【发布时间】:2017-07-26 09:38:39
【问题描述】:

我正在尝试使用 $http 方法从 angular 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);
        });

但我仍然收到此错误。

【问题讨论】:

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


    【解决方案1】:

    错误出现在指定的预检响应中。 所以你需要处理 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 请求(预检)以获取允许的来源、标头和方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2023-03-24
      • 2021-05-28
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多