安装相关包
npm i koa koa-router -S
npm i nodemon -S // 用来启动服务(保存文件自动热更)
根目录新建启动文件(serve.js)
const Koa = require('koa');
const KoaRouter = require('koa-router');
const app = new Koa();
const router = new KoaRouter();
app.use(router.routes());
app.use(router.allowedMethods());
router.get('/', (ctx, next) => {
ctx.body = 'koa服务器启动中';
});
app.listen('3006', (err) => { // 端口可自行设置
if (err) {
console.log('服务器失败');
} else {
console.log('服务器启动成功:地址为:http://localhost:3006');
}
});
启动
nodemon sever.js
打开 http://localhost:3006
post请求处理
安装解析request body的插件
npm i koa-bodyparser -S
代码改为
const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaBodyParser = require('koa-bodyparser'); // ** 新增
const app = new Koa();
const router = new KoaRouter();
app.use(KoaBodyParser()); // ** 新增
app.use(router.routes());
app.use(router.allowedMethods());
router.get('/', (ctx, next) => {
ctx.body = 'koa服务器启动中';
});
// ** 新增
router.post('/v1/login', (ctx, next) => {
console.log(ctx.request.body); // 获取请求体 这里有坑,后续会说
const {
request: { body }
} = ctx;
if (body.username !== 'admin' && body.password !== 'admin') { // 常规判断
ctx.body = {
error: 1,
msg: '用户名或密码错误'
};
return;
}
ctx.body = {
error: 0,
data: {
...body
}
};
});
app.listen('3006', (err) => {
if (err) {
console.log('服务器失败');
} else {
console.log('服务器启动成功:地址为:http://localhost:3006');
}
});
一个post类型的接口就OK了
问题: 打印ctx.request.body 为 undefined
解决:
- 安装 koa-bodyparser
- app.use(KoaBodyParser()) 一定要在 app.use(router.routes()) 之前
注意:这里打印 ctx.request 还是没有 body 的任何信息
要想查看body的内容直接打印“ctx.request.body”,就会显示body的具体内容