javascriptnode.jsjsonkoakoa-router

When using PUT method body is not passed using Koa


I am trying to make update function, where a user can put the new data and the data in the server would get updated, a simple task, however, when I try to PUT new data, the body is always undefined.

The data which gets sent:

  request: {
    method: 'PUT',
    url: '/api/v1.0/articles/1',
    header: {
      'user-agent': 'PostmanRuntime/7.17.1',
      accept: '*/*',
      'cache-control': 'no-cache',
      host: 'localhost:3000',
      'accept-encoding': 'gzip, deflate',
      'content-length': '98',
      connection: 'keep-alive'
    }
  },
  response: {
    status: 404,
    message: 'Not Found',
    header: [Object: null prototype] {}
  },

Now I tried passing it as keys using other methods and not RAW method, this is what is inside of the body I am trying to pass:

{
    "title": "another article",
    "fullText": "again here is some text hereto fill the body"
}

This is the function which should update the data, but it gets undefined from the put request.


router.put("/:id", updateArticle);

function updateArticle(cnx, next) {
  let id = parseInt(cnx.params.id);
  console.log(cnx);
  if (articles[id - 1] != null) {
    //articles[id - 1].title = cnx.request.body.title;
    cnx.body = {
      message:
        "Updated Successfully: \n:" + JSON.stringify(updateArticle, null, 4)
    };
  } else {
    cnx.body = {
      message:
        "Article does not exist: \n:" + JSON.stringify(updateArticle, null, 4)
    };
  }
}

I am using postman, Body -> Raw | JSON, I do have to mention all other methods work perfectly - delete, create, getAll, getById


Solution

  • With a PUT or POST, the data is in the body of the request. You have to have some code (in your request handler or some middleware) that actually reads the body from the stream and populates the body property for you. If you don't have that, then the data is still sitting in the request stream waiting to be read.

    You can see an example of reading it yourself here: https://github.com/koajs/koa/issues/719 or there is pre-built middleware that will do that for you.

    Here's are a couple modules that will do that middleware for you:

    https://github.com/dlau/koa-body

    https://www.npmjs.com/package/koa-body-parser