Koa实现一个简易登录

const Koa = require('koa')
const Router = require('koa-router')
const render = require('koa-art-template')
const static = require('koa-static')
const bodyParser = require('koa-bodyparser')
const session = require('koa-session')
const path = require('path')
let app = new Koa()

// 通过任意字符串为基准进行加密算法的字符串
app.keys = ['some secret hurr']
const CONFIG = {
  key: 'koa:sess',
  maxAge: 86400000,
  autoCommit: true,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: false
};

render(app, {
  root: path.join(__dirname, 'view'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
})

let router = new Router()
router.get('/', async ctx => {
  ctx.render('index')
}).post('/login', async ctx => {
    let username = ctx.request.body.username
    let password = ctx.request.body.password
    if (username !== 'abc' || password !== '123') {
      ctx.throw(400, '用户名或密码错误')
    } else {
      ctx.session.user = {username}
      ctx.body = '登录成功:' + ctx.session.user.username
    }

})

app.use(static(path.resolve('./public')))
app.use(session(CONFIG, app))

app.use(bodyParser())
app.use(router.routes())
  .use(router.allowedMethods())

app.on('error', (err,ctx) => {
  console.log(err)
  ctx.body = '有错了' + err
})

app.listen(8888)



    
    Title


这是首页

用户名:

密码:

 

你可能感兴趣的:(Node.js)