admin管理员组

文章数量:1297127

--- This question is pretty old and libraries used here are most likely outdated, the solution is still correct, but please use up-to-date versons ---

I am working on a web service with koa2 and node6. My koa dependencies as follows;

"koa": "^2.0.0-alpha.4",
"koa-async-body": "^1.0.4",
"koa-bodyparser": "^3.2.0",
"koa-logger": "^1.3.0",
"koa-router": "^7.0.1",

My implementation is like this;

const apiPrefix = 'api',
      apiParent = 'auth',
      api = 'register',
      router = new Router();

router.prefix(`/${apiPrefix}/${apiParent}/${api}`);

router.post('/', async(context, next) => {
  try {
    console.log(context.request.body);
    context.body = await post(context.request.body);
    await next();
  } catch (err) {
    context.throw(500);
  }
});

--- This question is pretty old and libraries used here are most likely outdated, the solution is still correct, but please use up-to-date versons ---

I am working on a web service with koa2 and node6. My koa dependencies as follows;

"koa": "^2.0.0-alpha.4",
"koa-async-body": "^1.0.4",
"koa-bodyparser": "^3.2.0",
"koa-logger": "^1.3.0",
"koa-router": "^7.0.1",

My implementation is like this;

const apiPrefix = 'api',
      apiParent = 'auth',
      api = 'register',
      router = new Router();

router.prefix(`/${apiPrefix}/${apiParent}/${api}`);

router.post('/', async(context, next) => {
  try {
    console.log(context.request.body);
    context.body = await post(context.request.body);
    await next();
  } catch (err) {
    context.throw(500);
  }
});

In another class, I bind this route to app. Also I have added bodyParser to the Koa as follows;

const app = new Koa();

app.use(bodyParser());

When I try to log the request body, it's an empty object. On the other hand, this setup works fine with other people in this project.

What am I doing wrong? Am I using an outdated dependency?

Share Improve this question edited Jan 14, 2022 at 12:33 Uğurcan Şengit asked Aug 9, 2016 at 17:14 Uğurcan ŞengitUğurcan Şengit 1,0261 gold badge12 silver badges31 bronze badges 3
  • 1 Did you have your routes registered after bodyParser? – Paweł Lula Commented Aug 14, 2016 at 18:36
  • Yes, I found out the problem actually. It was just because of I forget to add content-type header. – Uğurcan Şengit Commented Aug 14, 2016 at 18:37
  • Do routes need to be defined before bodyParser? – chovy Commented Sep 22, 2019 at 3:07
Add a ment  | 

1 Answer 1

Reset to default 10

Adding Content-type: application/json header to my Postman request, resolved the issue.

本文标签: javascriptKoa2 requestbody is emptyStack Overflow