Last active
April 14, 2023 04:00
-
-
Save crguezl/c0a8ee1b57626066b0031edb5ab769a7 to your computer and use it in GitHub Desktop.
express-session example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var session = require('express-session'); | |
var util = require('util'); | |
var app = express(); | |
app.use(session({ | |
secret: 'keyboard cat', | |
resave: false, | |
saveUninitialized: true, | |
name: "mycookiesession" | |
})); | |
app.use(function (req, res, next) { | |
var views = req.session.views; | |
(!views) && (views = req.session.views = {}); | |
// get the url pathname | |
var pathname = req.url; | |
console.log(`pathname = ${pathname}`); | |
// count the views | |
views[pathname] = (views[pathname] || 0) + 1 | |
next() | |
}) | |
app.get('/:chuchu', function (req, res, next) { | |
console.log(`req.params.chuchu = ${req.params.chuchu}`); | |
console.log(`req.session = ${util.inspect(req.session, {depth: null})}`); | |
res.send('you viewed this page ' + req.session.views['/'+req.params.chuchu] + ' times') | |
}) | |
var server = app.listen(3000, function () { | |
var host = server.address().address | |
var port = server.address().port | |
console.log('Example app listening at http://%s:%s', host, port) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "simple-example", | |
"version": "1.0.0", | |
"description": "", | |
"main": "hello-session.js", | |
"dependencies": { | |
"body-parser": "^1.15.0", | |
"cookie-parser": "^1.4.1", | |
"cookie-session": "^1.2.0", | |
"express": "^4.13.4", | |
"express-session": "^1.13.0", | |
"parse-url": "^1.3.0", | |
"parseurl": "^1.3.1" | |
}, | |
"devDependencies": {}, | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment