2

我使用 NodeJS 和 Express 编写了 web 服务。服务在 8090 端口上运行。另外我在 AngularJS 中编写了前端并在 8080 端口上运行。

Mongo 存储了所有用户的用户名和密码

当我通过 HTML5/AngularJS 前端登录时,AngularJS 应用程序依次调用 express 的 http post 请求。用户已通过身份验证。我设置 req.session.email = 用户的电子邮件地址。

我什至可以返回并检查 AngularJS 的控制台日志,说明 req.session.email 在 express 中设置正确

问题是我在 Express 中创建了一个名为“restrict”的身份验证函数,作为中间件函数,仅当 req.session.email 未定义时才授予对其他 get/post 请求的访问权限。

但是即使在设置了会话之后,当 AngularJS 应用程序调用 Express 的另一个 get/post 请求时,这个“限制”函数也会阻止调用,因为它接收到未定义的 req.session.email

AngularJS 和 Express 都在同一台机器上。但我不认为这是问题所在。

快速代码片段

var url = 'mongodb://127.0.0.1:5555/contacts?maxPoolSize=2';
var mongojs = require('mongojs');
var db = mongojs(url,['data']);
var dbauth = mongojs(url,['users']);
// var request = require('request');
var http = require('http');

var express = require('express');
var cookieparser = require('cookie-parser');
var app = express();



var bodyParser = require('body-parser');
var session = require('express-session');

app.use(cookieparser());
app.use(session({secret:'v3ryc0mpl!c@t3dk3y', resave: false, saveUninitialized: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

var user_session;

app.all('*',function(req, res, next){

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();

});

function restrict(req,res,next){


try{

    if(req.session.email){

        next();

    }
    else{

        res.send('failed');
        res.end();
    }

}
catch(err){

    res.send('failed');
    res.end();

}

};



app.post('/login',function(req,res){

//removed DB function from here to make the code look simple

        req.session.email = req.body.email;
        req.session.password = req.body.password;

});


app.get('/loggedin',restrict,function(req,res){


res.send(true);

});

AngularJS 函数调用 Express 函数来检查会话状态

var resolveFactory = function ($q, $http, $location,LoginDetails) {

var deferred = $q.defer();


$http.get("http://127.0.0.1:8090/loggedin")
    .success(function (response) {
        if(response == true){
            deferred.resolve(true);
        }
        else
        {
            deferred.reject();
            LoginDetails.setemail('');
            LoginDetails.setpassword('');
            $location.path("/");

        }
    })
    .error(function (err) {
        deferred.reject();
        $location.path("/");
     });

return deferred.promise;

};

从根本上说,我创建的 AngularJS Resolve Function 应该是成功的,但事实并非如此。它失败了。我正在使用 live-server 在我的笔记本电脑上运行 HTML/AngularJS 并使用 nodemon 来运行 Express 应用程序

4

1 回答 1

3

好的!所以原因是 AngularJS 在不同的端口 8080 上运行

{withCredentials: true}Express 在 8090 端口上运行。这意味着如果 AngularJS 调用 Express 的 API,除非 Express 允许将会话传递给 AngularJS 并且 AngularJS 调用具有参数集的 Express 的 API,否则 Express 的会话将丢失。以下是当 AngularJS 和 ExpressJS 在不同端口上运行时我必须进行的更改以保持会话

在 AngularJS 中,确保你调用 Express 的任何 API,它都应该是 {withCredentials: true}这样的

$http.get('http://expressdomainname:expressport/api',{withCredentials: true})

同样,如果您使用 $http.post 参数 {withCredentials: true} 很重要

现在在快递方面

确保你有这样的应用设置

app.all('*',function(req, res, next){

//Origin is the HTML/AngularJS domain from where the ExpressJS API would be called
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

//make sure you set this parameter and make it true so that AngularJS and Express are able to exchange session values between each other 
    res.header("Access-Control-Allow-Credentials", "true");
    next();

});

如果您对此主题有任何疑问,请随时问我问题。我花了几天时间来解决这个问题。

于 2015-11-09T16:04:08.713 回答