koa入门第一课:通过不同路由(url)及方法(method)返回不同结果(response)

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
    if (ctx.url === '/') {
        ctx.body = '这是主页';
    } else if (ctx.url === '/users') {
        if (ctx.method === 'GET') {
            ctx.body = '这是用户列表页';
        } else if (ctx.method === 'POST') {
            ctx.body = '创建用户';
        } else {
            ctx.status = 405;
        }
    } else {
        ctx.status = 404;
    }
});

app.listen(3000);
console.log('服务开启成功,请在打开浏览器运行:', 'http://localhost:3000');

猜你喜欢

转载自www.cnblogs.com/lihao97/p/12013841.html
今日推荐