As a whole, the connect framework is used to submit data with forms. The method of obtaining server-side form-data is described in the previous chapter. Each login verifies that its session.logged_in is true. If not, the form is displayed for login authentication; otherwise, login is displayed

session.js

var connect=require('connect')
,cookieSession=require('cookie-session')
,users=require('./users')
,morgan = require('morgan')
,multipart = require('connect-multiparty');
var server=connect()
    .use(cookieSession({
        name:'session'.keys: ['key1'.'key2'].maxAge:1000*30
    }))
    .use(morgan())
    .use(multipart())

    .use(function(req,res,next){
        if('/'==req.url&&req.session['logged_in'] = =true) {console.log('relogging')
            res.writeHead(200, {'Content-Type':'text/html'})
            res.end(`<h1>welcome back,<b>${req.session['name']}</b></h1><p><a>log Out</a></p>`)}else{
            next()
        }
    })
    .use(function(req,res,next){
        if('/'==req.url&&req.method=="GET") {console.log(req.session['logged_in'])
            res.writeHead(200, {'Content-type':'text/html'})
            res.end(`
      

username

password

`
)}else{ next() } }) .use(function(req,res,next){ if(req.url=="/login"&&req.method=="POST") {//console.log(req.body) res.writeHead(200) if(req.body.password! =users[req.body.username].password||! users[req.body.username].password){ res.end('Wrong password')}else{ req.session.logged_in=true req.session['name']=users[req.body.username].name res.end('Authenticated')}}else{ next() } }) .use(function(req,res,next){ if('/logout'==req.url&&req.method=="GET"){ req.session['logged_in'] =false; res.writeHead(200) res.end("Logged out")}else{ next() } }) server.listen(3000) Copy the code

Session is not saved after refreshing, still need to be improved…. I asked my senior brother, and found a problem that I had neglected before: REq should be written before RES. I was stupid, I really was. There you go.

    .use(function(req,res,next){
        if(req.url=="/login"&&req.method=="POST") {//console.log(req.body)
            
            if(req.body.password! =users[req.body.username].password||! users[req.body.username].password){ res.writeHead(200)
                res.end('Wrong password')}else{
                req.session.logged_in=true
                req.session['name']=users[req.body.username].name
                res.writeHead(200)
                res.end('Authenticated')}}else{
            next()
        }
    })
Copy the code