为什么bodyParser返回undefined?

问题描述 投票:0回答:1

我无法获得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)
node.js koa koa2
1个回答
1
投票

正文解析器用于解析POST请求(对于POST正文),在这里你必须使用req.query而不是req.body,跟进this问题。

© www.soinside.com 2019 - 2024. All rights reserved.