我正在尝试使更新函数,在那里用户可以放置新数据,服务器中的数据将得到更新,这是一个简单的任务,然而,当我尝试放置新数据时,主体总是未定义的。
发送的数据:
  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] {}
  },现在,我尝试使用其他方法而不是原始方法将其作为键传递,这是我试图传递的主体内部的内容:
{
    "title": "another article",
    "fullText": "again here is some text hereto fill the body"
}这是应该更新数据的函数,但它在put请求中没有定义。
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)
    };
  }
}我正在使用postman,Body -> Raw | JSON,我不得不提到所有其他方法都可以完美地工作- delete,create,getAll,getById
发布于 2019-09-27 06:17:10
使用PUT或POST时,数据在请求的主体中。您必须拥有一些代码(在您的请求处理程序或一些中间件中),以便从流中实际读取主体并填充body属性。如果没有,那么数据仍在请求流中等待读取。
你可以在这里看到一个自己阅读它的例子:https://github.com/koajs/koa/issues/719,或者有一个预先构建的中间件可以为你做到这一点。
下面是两个模块,它们将为您完成该中间件:
https://stackoverflow.com/questions/58124904
复制相似问题