在节点上使用 Express 在主页上捕获 Cookies (req.headers.cookie)

Capturing Cookies (req.headers.cookie) on homepage with Express on node

我正在做一个基本的身份验证示例。我有 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 并使用它来确定提供给客户端的内容?

设置 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');
  }
});

用Cookie的方法有点曲折,可以用cookie-parser,专为express而生

真的很简单,首页有例子:

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'));

我混合了应该由服务器处理什么和应该由客户端处理什么的范例。

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

检查 cookie