POST request body is undefined using koa-body

468 Views Asked by At

Its my first time trying to do a POST request with Postman using Koa in my application. I have the router and the body parser but for some reason i still get an error message sayng that my request body is undefined. I think the body parser is not working but i have no idea why.

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 message:

{}

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) ...

EDIT Also adding in server.js for further reference

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;
0

There are 0 best solutions below