3

this is my http code:

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

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

and the "/register" function is this (I am using 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);
}

I initially wanted to run what is commented out, to create a user. But when I do so I get a request error: ECONNREFUSED. So I just made it to console log what the body() actually is, but its empty. I have checked lots of websites and stack overflow posts yet no one has come across this bug where it doesn't identify my code. When I run it the way I just showed you I get this:

{ type: "json", value: Promise { <pending> } }
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
  • 4
    `console.log` does not return a promise, it makes no sense to `await` it. – zerkms Oct 28 '20 at 09:45
  • because if I were to do what I initially intended (register the user) it would need the await. I removed it but of course it still doesn't work – gabriel_tonini Oct 28 '20 at 09:56
  • I think it has something to do with server. Like the port number ? https://stackoverflow.com/questions/12687900/connection-attempt-failed-with-econnrefused-connection-refused-by-server – M A Salman Oct 28 '20 at 10:05

1 Answers1

3

Please try:

async register(ctx: RouterContext){
   console.log(await ctx.request.body().value);
}
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
  • The server sends the header first, and then the body. Router handlers are executed when the server responds with the headers but the body hasn't yet been sent, that's why we have to await for it too. – Santi Oct 31 '20 at 19:12