admin管理员组

文章数量:1357112

I am doing a basic authentication example. I have Node, Express, and Cookie. I make and store a cookie once the user logs in. Upon refreshing the page, I want to use the cookie to show that the user is still logged in on the response, and provide the information related to that user.

Server side:

// 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 ining_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 (ining_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.');
  }
});

How do I capture the cookies on the request to the homepage and use that to determine what is served to the client?

  • Do I put it in the JS on the client side?
  • If you want to suggest another node module, PLEASE show a working example in a plkr, fiddle, web page example, or the like. I do better studying working code, as it has taken me a bit long to get to this pont :)

Setting the cookie, also on the server side:

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

I am doing a basic authentication example. I have Node, Express, and Cookie. I make and store a cookie once the user logs in. Upon refreshing the page, I want to use the cookie to show that the user is still logged in on the response, and provide the information related to that user.

Server side:

// 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 ining_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 (ining_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.');
  }
});

How do I capture the cookies on the request to the homepage and use that to determine what is served to the client?

  • Do I put it in the JS on the client side?
  • If you want to suggest another node module, PLEASE show a working example in a plkr, fiddle, web page example, or the like. I do better studying working code, as it has taken me a bit long to get to this pont :)

Setting the cookie, also on the server side:

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');
  }
});
Share Improve this question edited Jun 3, 2015 at 19:26 chris Frisina asked Jun 3, 2015 at 14:40 chris Frisinachris Frisina 19.3k23 gold badges91 silver badges172 bronze badges 2
  • Where and how are you setting the cookie? – mscdex Commented Jun 3, 2015 at 15:02
  • @mscdex posted. Thanks for looking! – chris Frisina Commented Jun 3, 2015 at 18:26
Add a ment  | 

2 Answers 2

Reset to default 4

The method with Cookie is a bit devious, you can use cookie-parser, It's made for express.

It is really simple, there is a example on the home page:

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 mand that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

Or with your code:

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

I was mixing the paradigm of what should be handled by the server and what should be handled by the client.

Using Jquery addon 'jquery-cookie-master', I can check the cookie on the request of the client side with if ($.cookie('attributeWanted')){...}

本文标签: javascriptCapturing Cookies (reqheaderscookie) on homepage with Express on nodeStack Overflow