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

*爱你&永不变心* 提交于 2019-12-10 01:17:44
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');
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!