8

I'm trying to build a react/node application and I was trying to pass a value which I get from user input to the nodejs api to call a separate api (Instagram API)

I want to attach an object to req.body from React app. I want to do something like this:

app.get('/hashtags', (req,res) => {
   console.log(req.body);
   console.log(req.body.tag);
});

This is my responsible react app code for the above node request:

handleChange(e){
   const searchtag = 'hello';

   fetch('/hashtags', {
     method: 'GET',
     headers: {
       Accept: 'application/json',
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
       tag: searchtag,
     }),
   })
}

I'm calling handleChange function when I click a button. As for the above code I need my node api to call /hashtags with req.body.tag = 'hello' (as I'm passing 'hello' from reactjs).

But this gives me the following error:

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

If this can't be done this way: How can I attach an object to node api req.body from my react application?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Thidasa Pankaja
  • 930
  • 8
  • 25
  • 44

2 Answers2

3

If you want to pass string search tag why you are passing it in body. As per REST pass it in the url like this

 handleChange(e){
    const searchtag = 'hello';

    fetch('/hashtags/' + searchtag, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
     ),
    })
  }
shyam
  • 327
  • 2
  • 7
  • 1
    Yes, we can only able to send as params, but not as body, if you do so you will get TypeError: Body not allowed for GET or HEAD requests in fetch, I hope the same thing will happen in axios as well. – abhish Dec 06 '21 at 10:49
  • 1
    Sometimes you need to pass a lot of data and a url only goes up to 2048 characters. I guess REST isn't that great – ICW Feb 10 '22 at 18:52
  • You never need to pass that much data in a GET request, they're not supposed to handle large amounts of data. Generally if a lot of data is being sent over, it's for storing server side, so a PUT or POST should be used. – Alex Ander Mar 17 '22 at 10:44
  • Also, you can compress and/or encrypt the data sent in a URL as part of a GET request, which would make the data more compact and, if encrypted, more secure. – Alex Ander Mar 17 '22 at 10:45
-1
axios({
        method: 'GET',
        url: `${api.course}`,
        headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` },
        data:{'category': "Design"}
    })
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103