我试图在res.cookie
上使用res.append('Set-Cookie',...)
或express.js
设置Cookie,但是当我使用req.cookies
时,它会返回{}(这是默认设置res.cookies的价值)。我搜索了很多网页,但它仍然无法返回正确的值。 PS:Express是4.15.2
在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)
})
登录时,结果如下: cookie
但是当我请求/getAll
时,Cookie的控制台是:{}。 (默认值,而不是我们刚写的值)。
答案 0 :(得分:-1)
如果cookie和会话已正确使用,原因可能是: