初始化一个基于koa2的node服务器 & 接收post请求body 为 undefined

359 阅读1分钟

安装相关包

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

企业微信截图_84251338-e1ba-4b6e-aa16-43cd2d6a4acf.png

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

解决:

  1. 安装 koa-bodyparser
  2. app.use(KoaBodyParser()) 一定要在 app.use(router.routes()) 之前

注意:这里打印 ctx.request 还是没有 body 的任何信息

企业微信截图_2e3237a2-385a-4a69-a973-573aa8ec2ca6.png

要想查看body的内容直接打印“ctx.request.body”,就会显示body的具体内容