我观看了YouTube教程(https://youtu.be/hNinO6-bDVM?t=2m33s),其中将以下代码添加到Application
后,可以在开发人员工具的app.js
标签中看到Cookie:
var session = require('express-session');
app.use(session({
secret: 'keyboard cat',
name: 'testcookie',
resave: false,
saveUninitialized: true,
cookie: {
secure: false
}
}))
但是,我没有看到Cookie的运气。我觉得我已经尝试了几乎所有东西,但这就是我得到的一切:
这是我完整的app.js
文件:
var createError = require('http-errors');
var express = require('express');
var cookieParser = require('cookie-parser')
var path = require('path');
var logger = require('morgan');
var session = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/login');
var createSession = require('./routes/session');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/login', usersRouter);
app.use('/session', createSession);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.set('trust proxy', 1);
app.use(session({
secret: 'keyboard cat',
name: 'testcookie',
resave: false,
saveUninitialized: true,
cookie: {
secure: false
},
proxy: true
}))
module.exports = app;
您知道可能会丢失什么吗?我是Express的新手,这对我来说是一场难以置信的挣扎。预先谢谢你。
答案 0 :(得分:1)
In order to set a cookie in express
while using cookie-parser
middleware you must provide an endpoint/route to supply the cookie. In a route handler add the code
res.cookie(“myCookieName”, {value: “some-value”})
And the client will receive the cookie upon visiting that route.
Now on each request the end-user makes the cookie will be sent to your server automatically and parsed with cookie-parser
. Each cookie we have set can then be accessed by name on the req.cookie
object while handling it an incoming request in the route handler body.
If you would like to set any options while setting a cookie all options such as expired
and maxAge
can be found in the
cookie-parser
docs.