Post请求 Cannot read property 'body' of undefined

来源:4-2 mongoose(2)

慕运维6332306

2020-04-12

老师,为什么 找不到body这个属性?是哪里出错了?
users.js

const router = require("koa-router")();
const Person = require("../dbs/models/person");

router.prefix("/users");

router.get("/", function (ctx, next) {
  ctx.body = "this is a users response!";
});

router.get("/bar", function (ctx, next) {
  ctx.body = "this is a users/bar response";
});

//定义一个add操作数据库
router.post("/addPerson", async function (ctx) {
  global.console.log(ctx.request.body.name);
  global.console.log(ctx.request.body.age);

  try {
    //实例化Person的model
    const person = new Person({
      name: ctx.request.body.name,
      age: ctx.requests.body.age,
    });

    global.console.log(ctx.request.body.age);
    let code;
    await person.save();

    code = 0;
  } catch (error) {
    console.log(error);
    
    code = -1;
  }

  ctx.body = {
    code: code,
  };
});

module.exports = router;

person.js

// import mongoose from "mongoose";  es6 语法不支持
const mongoose = require("mongoose");

//schema 描述数据库的一些字段  model 是具备了数据库的一些行为操作 curd
let personSchema = new mongoose.Schema({
  name: String,
  age: Number,
});

//将创建的schema导出
module.exports = mongoose.model("Person", personSchema);

使用postman发送post请求

[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node bin/www`
pv: /users/addPerson
  <-- POST /users/addPerson
qin
28
TypeError: Cannot read property 'body' of undefined
    at E:\Code\code-vue\learn\koa2-learn\routes\users.js:23:25
写回答

1回答

Dolly_Zhang

2020-04-13

有启动路由吗?

app.use(router.routes())


0
0

Vue全家桶+SSR+Koa2全栈开发美团网

整合大前端8项技术,全面晋级全栈工程师,毕设/面试作品

2445 学习 · 1638 问题

查看课程