In the Express framework, sessions and cookies are not supported by default, but we can use third-party middleware: Express-session to solve this problem

1, install,

npm install express-session -S
Copy the code

2, configuration (must be before app.use(router))

app.use(session({
  // Configures the encryption string, which will be combined with the string to encrypt on the basis of the original encryption
  // The purpose is to increase security and prevent malicious forgery by clients
  secret: 'itcast'.resave: false.saveUninitialized: false // Whether you use Session or not, I assign you a key by default
}))

// Mount the route to the app
app.use(router)
Copy the code

3, use,

Once the plugin is configured, session data can be accessed and set via req.session

Adding Session Data

req.session.username = 'admin'
Copy the code

Accessing Session data

req.session.username
Copy the code