【问题标题】:HTTP does not recognize the bodyHTTP 无法识别正文
【发布时间】:2021-02-10 15:46:39
【问题描述】:

这是我的 http 代码:

POST http://localhost:8000/register
host: localhost:8000
Content-Type: application/json

{
    "id":111111,
    "name":"example",
    "email":"example@example.com",
    "password":"example"
}

“/register”函数是这样的(我正在使用react):

async register(ctx : RouterContext){
    await console.log(ctx.request.body());
   // const { value: {id,name, email, password} } = await ctx.request.body();

   // const user = await User.findOne({email})
   // if (user) {
   //     ctx.response.status = 422;
   //     ctx.response.body = {message : "Email is already in use"};
   //     return;
   // }
   // console.log(id,name, email, password);
}

我最初想运行注释掉的内容来创建用户。但是当我这样做时,我收到一个请求错误:ECONNREFUSED。所以我只是让它来控制台记录 body() 实际上是什么,但它是空的。我检查了很多网站和堆栈溢出帖子,但没有人遇到过这个无法识别我的代码的错误。当我按照我刚刚向您展示的方式运行它时,我得到了这个:

{ type: "json", value: Promise { <pending> } }

【问题讨论】:

  • console.log 不返回承诺,await 它没有任何意义。
  • 因为如果我要按照我最初的意图(注册用户)进行操作,则需要等待。我删除了它,但它当然仍然不起作用
  • 我认为它与服务器有关。喜欢端口号? stackoverflow.com/questions/12687900/…

标签: javascript reactjs typescript deno


【解决方案1】:

请尝试:

async register(ctx: RouterContext){
   console.log(await ctx.request.body().value);
}

【讨论】:

  • 服务器先发送header,再发送body。当服务器响应 headers 但 body 尚未发送时,将执行路由器处理程序,这就是为什么我们也必须等待它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多