Skip to content

Instantly share code, notes, and snippets.

@maylisdoucet maylisdoucet/app.js
Created Apr 16, 2018

Embed
What would you like to do?
Initialiser les sessions via le middleware
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var usersRouter = require('./routes/users');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// PARTIE RAJOUTEE (début)
const Session = require('express-session');
const FileStore = require('session-file-store')(Session);
app.use(Session({
store: new FileStore({
path: path.join(__dirname, '/tmp'),
encrypt: true
}),
secret: 'Super Secret !',
resave: true,
saveUninitialized: true,
name : 'sessionId'
}));
// PARTIE RAJOUTEE (fin)
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/users', usersRouter);
// 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');
});
module.exports = app;
var express = require('express');
var router = express.Router();
router.get('/session-in', (req, res) => {
// Initialisation de la variable de sessions "song".
req.session.song = 'be bop a lula';
res.end('ouverture de session');
});
router.get('/session-out', (req, res) => {
// VARIABLE affichée en sortant de la session.
res.send(req.session.song + 'est le son de cette session');
});
module.exports = router;
// Dans ton dossier contenant ton projet généré avec l'express-generator,
// tu vas créer deux nouvelles routes dans le fichier routes/index.js.
// Une route /session-in dans laquelle tu initialiseras une variable de session (song)
// contenant be bop a lula.
// Attention, l'écriture en session se fera seulement lorsque la réponse sera envoyée à l'utilisateur par exemple via res.send() ou res.render() ou res.end().
// Une route /session-out qui affichera le contenu de la variable de session song
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.