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).