Pass payload in GET request React fetch

旧时模样 提交于 2021-01-27 14:19:51

问题


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?


回答1:


If you want to pass string serach 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',
      },
     ),
    })
  }


来源:https://stackoverflow.com/questions/48187482/pass-payload-in-get-request-react-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!