使用Express on node在主页上捕获Cookie(req.headers.cookie)

时间:2015-06-03 14:40:54

标签: javascript node.js cookies server-side

我正在做一个基本的身份验证示例。我有Node,Express和Cookie。我在用户登录后制作并存储cookie。刷新页面后,我想使用cookie来显示用户仍然登录响应,并提供与该用户相关的信息。

服务器端:

// If I put the app.get('/'.....) up here I get the response, but not the page HTML/JS/CSS/etc...

// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));

// Here I get the page HTML/JS/CSS/etc but can't capture the cookie
app.get('/', function(req, res) {
  console.log('I want to get here');
  if(req.headers.cookie){ 
    // This parses the cookies into a usable array
    var incoming_cookies = cookie.parse(req.headers.cookie);
    Person.find({...})
      .then( function(results) {
        if (weDontFindSomeone) {
          console.log('user not found');
          res.status(400).send('user not found');
        } else {
          if (incoming_cookies.uname === loggedIn.uname) {
            console.log('Starting with a cookie logged in');
            res.status(200).send(results);
          } else {
            console.log('Some other problem with cookies');
            res.status(400).send('Some other problem with cookies');
          }
        }
      })
      .catch(function(error){
         res.status(400).send('some other error in starting, error: ' + error);
      });
  } else {
    res.status(200).send('Starting from scratch.');
  }
});

如何在请求主页上捕获cookie并使用它来确定向客户提供的内容?

  • 我是否将它放在客户端的JS中?
  • 如果您想建议另一个节点模块,请在plkr,小提琴,网页示例等中显示一个工作示例。我更好地学习工作代码,因为它花了我一点时间才到达这个pont:)

设置cookie,也在服务器端:

app.post('/api/login', function (req, res) {
  console.log('Getting a login request');
  if (weValidateTheCredentials) {
    Person.find({...})
      .then(function(personResults) {
        if (personResults.rowCount === 0) {
          res.status(400).send('user not found');
        } else {
          console.log('Logging in at \'/api/login\', and sending a cookie.');
          // 3 hours max age
          res.cookie('UID', req.body.uid, {maxAge: 10800000});
          res.cookie('uname', req.body.uname, {maxAge: 10800000});
          res.status(200).send(personResults);
        }
      })
      .catch(function(error){
          res.status(400).send('some other error in logging in, error: ' + error);
      });
  } else {
    res.status(400).send('login requires a uname and pwhash');
  }
});

2 个答案:

答案 0 :(得分:1)

使用Cookie的方法有点狡猾,您可以使用cookie-parser,它是为快递而制作的。

这很简单,主页上有一个例子:

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

或者使用您的代码:

var cookieParser = require('cookie-parser');

// Add cookie parser
app.use(cookieParser());

app.get('/', function(req, res) {
  console.log('I want to get here');
  if(req.cookies){ 
    Person.find({...})
      .then( function(results) {
        if (weDontFindSomeone) {
          console.log('user not found');
          res.status(400).send('user not found');
        } else {
          if (req.cookies.uname === loggedIn.uname) {
            console.log('Starting with a cookie logged in');
            res.status(200).send(results);
          } else {
            console.log('Some other problem with cookies');
            res.status(400).send('Some other problem with cookies');
          }
        }
      })
      .catch(function(error){
         res.status(400).send('some other error in starting, error: ' + error);
      });
  } else {
    res.status(200).send('Starting from scratch.');
  }
});

// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));

答案 1 :(得分:0)

我正在混合应该由服务器处理的内容以及客户应该处理的内容。

使用Jquery插件' jquery-cookie-master',我可以根据if ($.cookie('attributeWanted')){...}

的客户端请求检查cookie