在 GET 请求 React fetch 中传递有效负载

Thi*_*aja 5 javascript fetch node.js reactjs

我正在尝试构建一个 react/node 应用程序,并且试图将从用户输入中获得的值传递给 nodejs api 以调用单独的 api(Instagram API)

我想从 React 应用程序将一个对象附加到 req.body。我想做这样的事情:

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

这是我负责上述节点请求的反应应用程序代码:

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

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

handleChange单击按钮时,我正在调用函数。至于上面的代码,我需要我的节点API调用/hashtagsreq.body.tag = 'hello'(作为我传递'hello'从reactjs)。

但这给了我以下错误:

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

如果这不能通过这种方式完成:如何将对象req.body从我的反应应用程序附加到节点 api ?

shy*_*yam 3

如果您想传递字符串搜索标签,为什么要将其传递到body. 按照REST这样的方式在 url 中传递它

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

    fetch('/hashtags/' + searchtag, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
     ),
    })
  }
Run Code Online (Sandbox Code Playgroud)