为什么bodyParser返回未定义?

时间:2019-03-31 04:47:22

标签: node.js koa koa2

我无法获得POST http://127.0.0.1:3001/users?name=Slava的请求正文。

服务器响应“名称是必需的”。方法getUsers可以正常工作。 RethinkDB运作良好,server.js也运作。我在这里搜索了类似的答案,但是没有合适的答案。答案很老,但是没有关系。

这是请求:http://127.0.0.1:3001/users?name=bob(我使用Postman进行POST)

为什么bodyParser在我的代码中不起作用?我不知道为什么会这样。

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)

1 个答案:

答案 0 :(得分:1)

Body解析器用于解析POST请求(用于POST正文),在这里您必须使用req.query而不是req.body,然后继续this问题。

相关问题