入口文件:index.js可自行定義名字,很少說。express
const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa() const bodyParser = require('koa-bodyparser'); const router = new Router(); const session = require('koa-session'); const cors = require('koa2-cors'); const userlogin=require('./routes/userlogin') const registerNewUser=require('./routes/registerNewUser') app.use(session(app)) app.use(bodyParser({ enableTypes:['json','text','form'] })) app.use(cors({ origin: 'http://localhost:3000', exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 5, credentials: true, allowHeaders: ['Content-Type', 'Authorization', 'Accept'], })); router.post('/userlogin',userlogin) router.post('/registerNewUser',registerNewUser) // router.get('/post', ctx => { // ctx.body = ctx.request.body // }) app.use(async (ctx, next) => { console.log(ctx.request.path+':'+ctx.request.method); await next(); }); app .use(router.routes()) .use(router.allowedMethods()) server.listen(3007)
子路由文件registerNewUser.js export一個函數(在express中使用的是module.exports=router)json
module.exports=(ctx,next)=>{ let registerUser=ctx.request.body.userInfo console.log(registerUser) if(registerUser.new_password==registerUser.new_password1){ ctx.body={registerState:'success',msg:'註冊成功'}; }else{ ctx.body={registerState:'error',msg:'註冊失敗,兩次密碼不對應'} } next() }
一樣的,子路由文件userlogin.js export一個函數session
module.exports= async function userlogin(ctx,next) { let loginUser=ctx.request.body.userInfo const users=[ ] let userMatched={}; for(let index in users){ if(users[index].username==loginUser.username){ userMatched=users[index] } } if(userMatched.password==loginUser.password){ ctx.body={loginState:'success',msg:'登錄成功',user:userMatched}; }else{ ctx.body={loginState:'error',msg:'用戶名或密碼錯誤'} } next() }
是否是很簡單。app