Sessions
- Sessions are a server-side data store that we use to make HTTP stateful. Instead of storing data using cookies, we store the data on the server-side and then send the browser a cookie that can be used to retrieve the data.
- It's not very practical or secure to store a lot of data client-side using cookies. This is where sessions come in.
Express Session
- install : npm i express-session
- Example
const session = require('express-session');
app.use(session({secret: 'thisissecret'}));
app.get('/viewcount', (req, res) => {
if (req.session.count) {
req.session.count += 1;
//The information is stored in the JS memory store by default,
//which is not recommended in production.
} else {
req.session.count = 1;
}
res.send(`You have viewed this page ${req.session.count} times.`);
})
Flash
- A place in the session used for storing messages.
- Messages are written to the flash and cleared after being displayed by the user.
- Typically used in combination with redirects.
- Example
app.get('/flash', (req, res) => {
req.flash('info', 'Flash is back');
res.redirect('/');
})
app.get('/', (req, res) => {
res.render('index', {messages: req.flash('info')});
//second argument : get an array of flash messages by passing the key to req.flash()
//This message can be used in HTML template now.
})
res.locals
- An object that contains response local variables scoped to the request, and therefore available only to the views rendered during that request/response cycle (if any).
- Example
app.use((req, res, next) => {
res.locals.messages = req.flash('success');
next();
})
* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.
'TIL: Today I Learned' 카테고리의 다른 글
[TIL] 20210412 자바스크립트란? (0) | 2021.04.12 |
---|---|
[TIL] 20201228 Authentication from "Scratch" (0) | 2020.12.28 |
[TIL] 20201222 Express Router & Cookies (0) | 2020.12.22 |
[TIL] 20201221 Data Relationships With Mongo (0) | 2020.12.21 |
[TIL] 20201219 Handling Errors in Express Apps (0) | 2020.12.19 |