Do not get body from fetch/POST request


#1

Im using fetch in a client script to make a POST request to my server controller. So far no problem. The server answers with the JSON-Data defined in the controller. The only problem is that I’m unable to read the posted body object in the controller.

This ist the POST request from the client:

var myHeaders = new Headers()
myHeaders.append('content-type', 'application/json')
    
   fetch('amsbam/data', {
      method: 'POST',
      headers: myHeaders,
      body: JSON.stringify('{"name": "ingo"}')

    })
    .then(result => {
    	console.log('SUCCESS')
     	result.json()
      
    })
    .then(j => {
    	console.log(j)
    })
    .catch(err => {
    	console.log("ERR: ", err)
    });

And this is my controller. As mentioned before, it sends the response but request.all() and request.body are {}.

async fetch ({request, response}) {
   const data = await request.all()
   console.log(data, request.body)
   response.send([{name:'ingo'}])
} 

What do I have to do to read the body from my fetch request?
Is it maybe a security issure in adonis? I have already added the route to the csrf exeption list.


#2

all function is not async, so remove await keyword.


#3
  1. make sure on you have listed your fetch method on your route.js file

  2. to return json response, example : return response.status(200).json({message : 'success', data : data})

  3. you should use try - catch block, to make sure you catch error or exception and you can return it as json response as well , example :

try{
......
return response.status(200).json({message : 'success', data : data})
}catch(exception)
{
return response.status(404).json({message : 'error'})
}

and my last suggestion, you don’t need await while you get the value from request.all() though is still work even you don’t remove it, but it’s not a proper way…request.all() is not a promise, so await won’t be needed


#4

I’m actually running into this same issue, but I’m using postman to test it. All that is getting logged is an empty object: { }. Interestingly, if i try to log request.raw() I get the right response{"name": "testyMcTasteFace"} but if i try to log raw.name it logs undefined. I’m using Basic Auth and have disabled CSRF. Any help is greatly appreciated. Thanks in advance

   async store ({ request, response, auth }) {
    try {
      const data = request.all()
      const raw = request.raw()
      console.log(data)
      console.log(raw)
      console.log(raw.name)
    }
    catch(error){
        console.log(error)
     }
    }

EDIT:

I’m dumb… idk what happened. raw.name works and I can log the data now. I did some dumb testing. but yeah anyway, this does seem to get the data for me. @queerdancer