@narem

Как создать сессию?

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)

В чем проблема? Почему не определяет
  • Вопрос задан
  • 330 просмотров
Решения вопроса 1
lastuniverse
@lastuniverse
Всегда вокруг да около IT тем
как показано в описании client-sessions помимо опции secret надо задать еще ряд опций, таких как cookieName (она же имя сессии) либо requestKey (requestKey overrides cookieName for the key name added to the request object).
что позволит обращаться к сесcии через 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}`);
});


PS: и не забывайте вызывать next(); там где требуется передать управление следующему обработчику или же request.end() или request.send(...) там где требуется прекратить дальнейшую обработку запроса

PSPS: и пожалуйста, напишите в чем у вас возникли проблемы с ранее предложенным решением или отметьте его решением.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы