nodejs使用ajax调用和会话来休息服务

时间:2013-03-22 19:26:39

标签: jquery ajax node.js session

我构建了一个nodejs rest服务,我想设置一个auth系统。其余服务由来自

的ajax调用访问
$.get("http://localhost:3000/user",{},function(data){console.log(data)});

登录或者是ajax调用或者是来自浏览器的直接调用,我都不能坚持使用会话或cookie。

如果我获得登录成功,则下次通话

$.get("http://localhost:3000/user",{},function(data){console.log(data)});

服务器不知道我是谁。

nodejs文件

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

    if ('undefined' === typeof req.body.password || 'undefined' === typeof req.body.user) {

        res.redirect(req.headers.referer + '?error=-2');
        return;

    }

    mysql = tools.mysql();

    var user = req.body.user,
        password = crypto.createHash('md5').update(req.body.password).digest("hex"),
        result = {
            result: 0
        },
        check,
        id,
        value;

    mysql.query('SELECT id, level, nome FROM chaves_proatlantico.utilizadores WHERE email = ? and password = ?;', [user, password])
        .on('result', function (rows) {

            check = crypto.createHash('md5').update(req.socket.remoteAddress + '' + Date.now()).digest("hex");
            id = crypto.createHash('md5').update(user + password).digest("hex");
            value = {
                id: id,
                check: check
            };
            req.session.user = rows.id;
            req.session.level = rows.level;
            req.session.name = rows.nome;
            req.session.id = id;
            req.session.check = check;

            result.result = 1;

            res.cookie('restid', JSON.stringify(value), { maxAge: 900000, httpOnly: false });

            mysql.query('UPDATE chaves_proatlantico.utilizadores SET code = ? WHERE email = ? and password = ?;', [check, user, password]).on('end', function () {
                tools.mysqlend();
            })
                .on('end', function () {
                    tools.mysqlend();
                    res.redirect(req.headers.referer + '?id=' + id + '&check=' + check);
                })
                .on('error', function (err) {
                    result = {result: -1, data: err.code};
                });

        })
        .on('end', function () {
            if (1 !== result.result) {
                tools.mysqlend();
                res.redirect(req.headers.referer + '?error=' + result.result);
            }
        })
        .on('error', function (err) {
            result = {result: -1, data: err.code};
        });

});
app.get('/user', tools.requiredLogin, function (req, res) {

      var result = {
                result: 1,
                data: {
                    name: req.session.name
                }
            };
        tools.json(req, res, result);
    });

0 个答案:

没有答案