const Koa = require(‘koa‘) const app = new Koa() app.use((ctx, next)=>{ if(ctx.request.method === ‘GET‘){ ctx.response.body = ‘hello world‘ } }) app.listen(8000, ()=>{ console.log(‘8000端口启动‘) })
const Koa = require(‘koa‘) const app = new Koa() const Router = require(‘koa-router‘) const userRouter = new Router({ prefix: ‘/user‘ }) app.use((ctx, next) => { next() }) userRouter.post(‘/‘, (ctx, next)=>{ ctx.response.body = ‘post请求‘ }) app.use(userRouter.routes()) app.listen(8000, () => { console.log(‘8000端口启动‘) })
const Koa = require(‘koa‘) const app = new Koa() const Router = require(‘koa-router‘) const userRouter = new Router({ prefix: ‘/user‘ }) app.use((ctx, next) => { next() }) userRouter.get(‘/:id‘, (ctx, next)=>{ ctx.response.body = { query: ctx.request.query, params: ctx.request.params } }) app.use(userRouter.routes()) app.listen(8000, () => { console.log(‘8000端口启动‘) })
const Koa = require(‘koa‘) const app = new Koa() const bodyParser = require(‘koa-bodyparser‘) const Router = require(‘koa-router‘) const userRouter = new Router({ prefix: ‘/user‘}) app.use(bodyParser()) userRouter.post(‘/‘, (ctx, next)=>{ ctx.response.body = ctx.request.body }) app.use(userRouter.routes()) app.listen(8000, ()=>{console.log(‘开启8000端口‘)})
const Koa = require(‘koa‘) const app = new Koa() const Router = require(‘koa-router‘) const userRouter = new Router({ prefix: ‘/user‘}) const multer = require(‘koa-multer‘) const upload = multer() userRouter.post(‘/‘, upload.single("file"), (ctx, next)=>{ ctx.response.body = { body: ctx.req.body, file: ctx.req.file } }) app.use(userRouter.routes()) app.listen(8000, ()=>{console.log(‘开启8000端口‘)})
const Koa = require(‘koa‘) const app = new Koa() app.use((ctx, next)=>{ ctx.app.emit(‘error‘, new Error(‘请先登录‘), ctx) }) app.on(‘error‘, (err, ctx)=>{ ctx.body = err.message; }) app.listen(8000, ()=> {})
原文:https://www.cnblogs.com/vigourice/p/15116366.html