【问题标题】:Angular2, NodeJS & Passport IssueAngular2、NodeJS 和护照问题
【发布时间】:2017-02-20 12:53:21
【问题描述】:

目前我的 Angular2 前端在 localhost:3000 上运行,NodeJS 后端(基于 KrakenJS)在 localhost:8000 上运行。当我输入凭据时,我调用了this.http.post('http://localhost:8000/login', body, { headers: contentHeaders }) api,但我在 Chrome 中得到了以下响应:

XMLHttpRequest cannot load http://localhost:8000/login. The request was redirected to 'http://localhost:8000/', which is disallowed for cross-origin requests that require preflight.

但是当我调用 this.http.post('http://localhost:8000/register', body, { headers: contentHeaders }) 时,它一切正常,并且完成了所有的注册魔法(散列 pswd,在数据库中存储详细信息等)。

这是我来自 (register.js) 的简单注册 API:

 router.post('/', function (req, res) {

    if (req.body.email && req.body.password) {
        var User = require('../../models/user');

        User.create({
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
        }).then(
            function() {
                res.render('user/registered', {registered: true});
            },
            function() {
                res.render('user/registered', {registered: false});
            }
        );
    } else {
        res.render('user/registered', {registered: false});
    }
});

这是来自 (login.js) 的登录 api:

 router.post('/', function (req, res) {

    passport.authenticate('local', {
        successRedirect: req.session.goingTo || '/',
        failureRedirect: '/login',
        failureFlash: true
    })(req, res);

});

【问题讨论】:

    标签: javascript node.js angular passport.js


    【解决方案1】:

    在您的主服务器文件中启用 CORS:

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    

    【讨论】:

    • * 不应该是您的 Access-Control-Allow-Origin 标头值。它违背了浏览器安全功能的目的。
    猜你喜欢
    • 2015-05-05
    • 2012-09-13
    • 2023-04-06
    • 1970-01-01
    • 2020-10-28
    • 2019-08-12
    • 2017-12-05
    • 2017-05-29
    • 2016-03-18
    相关资源
    最近更新 更多