-1

I'm trying to set cookie using res.cookie or res.append('Set-Cookie',...) on express.js, but when I use req.cookies, it return {}(which is the default value of res.cookies). I've searched many web pages but it still can't return the right value. PS: Express is 4.15.2


in server.js:


var express = require('express');

var session = require('express-session');//设置session

var cookieParser = require('cookie-parser');//解析cookie

var bodyParser = require('body-parser');

var app = express();

app.use(express.static('public'));

app.use(session({

  secret: 'keyboard cat',

  cookie: { maxAge: 60000 },

  resave: false,

  saveUninitialized: true

}));

app.use(bodyParser.urlencoded({extended: true}));

app.use(bodyParser.json());

app.use(cookieParser());

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
// 查询所有博客数据
app.get('/getAll',function(req,res){
    var pageNum = req.query.pageNum;
    //连接数据库
    query("some sql",function(err,vals,fields) {
      console.dir(req.session.id);
      // Cookies that have not been signed
      console.log('Cookies: ', req.cookies)
      // Cookies that have been signed
      console.log('Signed Cookies: ', req.signedCookies)
      res.send(vals);
    });
});
//登陆验证
app.post('/login',function(req,res){
var username = req.body.username;
var password = req.body.password;
//过滤
var sql = "some sql";
query(sql,function(err,vals,fields) {
  if(vals.length == 1){
    //登录成功
    //res.cookie('mycookie', '1234567890', { domain:'localhost',secure:false, maxAage:120000, httpOnly: true });
    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
    //   req.cookie('sid',req.session.id,{ maxAge: 900000, httpOnly: false});
    res.send("ok");
  }else{
    //登陆失败
    res.send("false");
  }
});
});

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/"+ "index_prod.html" );
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

When I login in, the result is as following: cookie

but when I request for /getAll ,the console for cookies are: { }. (the default value, NOT the value we just write).

Tony
  • 1
  • 4
  • 1
    It's a little hard to see exactly what your question is. Are you asking why `req.cookies` is an empty object inside the `getAll` route handler? Are you 100% sure that the cookie-parser module is loading successfully? FYI, `res.cookie()` is used for setting cookies. Your question mentions `res.cookies` which is not a valid property name. You should either be using `res.cookie()` to set a cookie or `req.cookies` to read cookies that arrived with the request. `req.cookies` needs the cookie-parser middleware in order to be set. – jfriend00 Mar 28 '17 at 02:55
  • Thanks, I have got the reason. – Tony Mar 28 '17 at 03:18

1 Answers1

-1

If the cookies and session have been correctly used, the reasons may be :

  1. Make sure the client and the server obey the Same-origin policy. If not, make some changes.
  2. Make sure your websites have no errors. (In the code above, there exit other errors such as 404 (Not Found) in the process of images fetching)
Tony
  • 1
  • 4