javascriptnode.jsreactjsaxios

body data not sent in axios request


I am trying to send data through axios request to my backend script, but the body looks empty.

Here's a request sent from front-end:

axios.request({
  method: 'GET',
  url: `http://localhost:4444/next/api`,
  headers: {
    'Authorization': token
  },
  data: {
    next_swastik: 'lets add something here'
  },

}).then((res)=>{  
  console.log("api call sucessfull",res);

}).catch((err)=>{
  console.log("api call unsucessfull",err);

  this.props.toggleLoading(false);
})

Here's a back-end:

app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);

})

But I am getting {} empty body. I am getting headers and other data but not data.


Solution

  • Not all clients and servers support body in GET request. In this case, the browser can't send body in GET request (axios supports sending body in GET request).

    As a workaround, you can change the method from 'GET' to 'POST'

    Like so:

    axios.request({
      method: 'POST',
      url: `http://localhost:4444/next/api`,
      headers: {
        'Authorization': token
      },
      data: {
        next_swastik: 'lets add something here'
      },
    
    })
    

    and change your api to expect a post

    app.post('/next/api', verifyToken, function(req, res) {
    console.log(req.body);
    });
    

    or

    Change the data property to params

    axios.request({
      method: 'GET',
      url: `http://localhost:4444/next/api`,
      headers: {
        'Authorization': token
      },
      params: {
        next_swastik: 'lets add something here'
      },
    
    })
    

    and change the api to log out the params

    app.get('/next/api', verifyToken, function(req, res) {
    console.log(req.params);
    });
    

    and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.