Answer the question
In order to leave comments, you need to log in
How to create a session?
const express = require('express'),
app = express(),
port = 3000,
clientSessions = require('client-sessions');
app.use(clientSessions({
secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK' // set this to a long random string!
}));
app.get('/',(request,response) => {
request.session.username = 'qwer';
});
app.get('/1',(request,response) => {
console.log(request.session.username);
});
app.listen(port,(err) => {
if(err){
return console.log(err);
}
console.log(`Слушается порт ${port}`);
});
TypeError: Cannot set property 'username' of undefined
at W:\domains\auth\index.js:11:30
at Layer.handle [as handle_request] (W:\domains\auth\node_modules\express\lib\router\layer .js:95:5)
at next (W:\domains\auth\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (W:\domains\auth\node_modules\express\lib \router\route.js:112:3)
at Layer.handle [as handle_request] (W:\domains\auth\node_modules\express\lib\router\layer.js:95:5)
at W:\domains\auth \node_modules\express\lib\router\index.js:281:22
at Function.process_params (W:\domains\auth\node_modules\express\lib\router\index.js:335:12)
at next (W:\ domains\auth\node_modules\express\lib\router\index.js:275:10)
at clientSession (W:\domains\auth\node_modules\client-sessions\lib\client-sessions.js:630:5)
at Layer.handle [as handle_request] (W:\domains\auth\node_modules\express\lib\ router\layer.js:95:5)
Answer the question
In order to leave comments, you need to log in
as shown in the description of client-sessions, in addition to the secret option, you need to set a number of options, such as cookieName (aka the session name) or requestKey (requestKey overrides cookieName for the key name added to the request object).
which will allow you to access the session through req
const express = require('express'),
app = express(),
port = 3000,
clientSessions = require('client-sessions');
app.use(clientSessions({
secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK', // set this to a long random string!
cookieName: 'ss', // cookie name dictates the key name added to the request object
requestKey: 'session', // requestKey overrides cookieName for the key name added to the request object.
}));
app.get('/',(request,response,next) => {
request.session.username = 'qwer';
response.send("вы обратились к /");
});
app.get('/1',(request,response,next) => {
console.log(request.session.username);
response.send("вы обратились к /1<br>в сессии сохранено: "+JSON.stringify(request.session));
});
app.listen(port,(err) => {
if(err){
return console.log(err);
}
console.log(`Слушается порт ${port}`);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question