Search code examples
node.jsfrontendfetchbackendkoa

How do I use the the post method with fetch and koa?


This is a function on my front-end that makes the request.

function postNewUser(){
    
    fetch(`http://12.0.0.1:8080/users/test`, {
        method: 'POST',
        body: {nome: name, email: "[email protected]", idade: 20}
    })
}

This is my back-end code to receive the request.

router.post('/users/:id', koaBody(), ctx => {
  ctx.set('Access-Control-Allow-Origin', '*');
  users.push(ctx.request.body)
  ctx.status = 201
  ctx.body = ctx.params
  console.log(users)
})

For some unknown reason I receive nothing. Not even a single error message. The "console.log()" on the back-end is also not triggered, so my theory is that the problem is on the front-end.

Edit

As sugested by gnososphere, I tested with Postman, and it worked. So now i know the problem must be on the fron-end code.


Solution

  • You can try your backend functionality with Postman. It's a great service for testing.

    the request would look something like this

    If the problem is on the frontend, double check your fetch method by posting to a website that will return data and logging that in your app.