Search code examples
node.jskoakoa2

Why bodyParser returns undefined?


I can't get body of request for the POST http://127.0.0.1:3001/users?name=Slava.

Server responce 'name is required'. Method getUsers work correctly. RethinkDB works good, server.js works too. I searched for similar answers here, but there is nothing suitable. There are very old answers, but they are not relevant.

This is request: http://127.0.0.1:3001/users?name=bob (I use Postman for POST)

Why bodyParser don't work in my code? I have no idea why this happens.

const Koa = require('koa')
const logger = require('koa-morgan')
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')
const r = require('rethinkdb')

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

const db = async() => {
    const connection = await r.connect({
        host: 'localhost',
        port: '28015',
        db: 'getteamDB'
    })
    return connection;
}

server.use(bodyParser());

const insertUser = async(ctx, next) => {
    await next()
    // Get the db connection.
    const connection = await db()

    // Throw the error if the table does not exist.
    var exists = await r.tableList().contains('users').run(connection)
    if (exists === false) {
      ctx.throw(500, 'users table does not exist')
    }

    let body = ctx.request.body || {}

    console.log(body);

    // Throw the error if no name.
    if (body.name === undefined) {
      ctx.throw(400, 'name is required')
    }

    // Throw the error if no email.
    if (body.email === undefined) {
      ctx.throw(400, 'email is required')
    }

    let document = {
      name: body.name,
      email: body.email
    }

    var result = await r.table('users')
      .insert(document, {returnChanges: true})
      .run(connection)

    ctx.body = result
  }

router
.post('/users', insertUser)

server
.use(router.routes())
.use(router.allowedMethods())
.use(logger('tiny')).listen(3001)

Solution

  • Body parser is used to parse POST requests (for POST body), here you have to use req.query instead of req.body, follow up this question.