使用koa-body未定义POST请求正文

问题描述

这是我第一次尝试在我的应用程序中使用Koa向Postman发出POST请求。我有路由器和正文解析器,但由于某些原因,我仍然收到一条错误消息,说我的请求正文未定义。我认为人体分析器无法正常工作,但我不知道为什么。

routes.js

const Koa = require('koa');
const bodyParser = require('koa-body')
const Router = require('koa-router')

const app = new Koa()
const router = new Router()

const Topic = require('./models/topic')

router.post('/topics',bodyParser(),async (ctx) => {
    console.log(JSON.stringify(ctx.request.body))

    const { name } = ctx.request.body
    newPost = {
        name: {name}
    }

    let newTopic = new Topic(newPost)

    await newTopic.save(function(error,newPost){
        if (error) {
            console.log(error)
        } else {
        
        res.status(201).json({
            message : 'Name added!'
            }).send(newPost)
        } 
    })

    return
})

app
  .use(router.allowedMethods())
  .use(router.routes())
  
module.exports = router

topic.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const TopicSchema = new Schema(
    {
        name: {type: String,required: true },viewCount: {type: Number,default: 0 }
    },{
        timestamps: true
    }
)

module.exports = mongoose.model('two/Topic',TopicSchema)

错误消息:

{}

Error: two/Topic validation Failed: name: Cast to string Failed for value "{ name: undefined }" at path "name"

at ValidationError.inspect (/home/node/app/node_modules/mongoose/lib/error/validation.js:47:26) ...

编辑 还添加了server.js以供进一步参考

const Koa = require('koa');
const mongoose = require('mongoose');

const router = require('./routes');


const app = new Koa();
app.use(require('koa-body')());
app.use(router.routes());

mongoose.connect(process.env.MONGODB_URI,{ useNewUrlParser: true,useUnifiedTopology: true })
    .then(() => {
        const listener = app.listen(process.env.APP_PORT || 3000,() =>
            console.log('App started on port ' + listener.address().port)
        )
    })
    .catch((error) => {
        console.log(error)
        process.exit(1)
    })

//    app.proxy = true;
module.exports = app;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)