ExpressJS设置/获取/使用cookie

时间:2013-10-25 13:50:20

标签: javascript node.js session cookies express

无法在请求中获取已设置的Cookie。

我用

设置我的cookie
response.cookie('name', 'My name');

我想以这种方式获取我的cookie,它之前有效,但我改变了快速配置,我现在不知道什么是问题。

request.cookies is and empty Object

我的快速配置:

var express = require('express'),
    api = require('./routes/api');

var app = express();

app.configure(function () {
   app.set('port', process.env.PORT || 3000);
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.json());
   //app.use(express.bodyParser());
   app.use(express.compress()); // New call to compress content
   app.use(express.cookieParser());
   app.use(express.session({secret: 'secret'}));
   app.use(app.router);
   app.use(express.methodOverride());
   //app.use(express.static(__dirname + '/public'));
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    next();
});

app.configure('development', function () {
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.errorHandler());
});

设置Cookie:

exports.singIn = function (req, res) {
    var mail = req.query.mail,
        password = req.query.password;

    return user.find({
        mail: mail
    }).then(function (d) {
        var user = usersData(u);

        res.cookie('mail', user.mail, { maxAge: 900000});
        res.cookie('password', crypted, { maxAge: 900000});
        res.json({ user: user });
        return { user: user }
    }).catch(function () {
        res.json(400, {"error-tag": "error-sing-in"});
        return {"error-tag": "error-sing-in"};
    });
};

获取Cookie:

exports.account = function (req, res) {
    var mail = req.cookies.mail,
        password = req.cookies.password;
    //here req.cookies is an empty object. I don't know why? 
};

2 个答案:

答案 0 :(得分:6)

2017年的答案..

const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());

从传入的请求中获取Cookie ..

let cookie = req.cookies['cookiename'];

设置响应cookie(此cookie将在所有未来的传入请求中发送,直到删除或到期)..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 86400 * 1000, // 24 hours
    httpOnly: true, // http only, prevents JavaScript cookie access
    secure: true // cookie must be sent over https / ssl
});

删除回复Cookie ..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 0
});

答案 1 :(得分:1)

当这是您需要的中间件功能时,使用额外的包(“cookie-parser”)有点夸张:

function cookieParser(req, res, next) {
  var cookies = req.headers.cookie;
  if (cookies) {
    req.cookies = cookies.split(";").reduce((obj, c) => {
      var n = c.split("=");
      obj[n[0].trim()] = n[1].trim();
      return obj
    }, {})
  }
  next();
}
app.use(cookieParser);

我无法在我的 graphQL 服务器中使用“cookie-parser”,因为它把事情搞砸了。