在GET请求中传递有效负载React Fetch [英] Pass payload in GET request React fetch

查看:37
本文介绍了在GET请求中传递有效负载React Fetch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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,
     }),
   })
}

单击按钮时,我正在调用 handleChange 函数.至于上面的代码,我需要我的节点api用 req.body.tag ='hello'调用/hashtags (因为我正在传递'hello'(来自reactjs).

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).

但这给了我以下错误:

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

如果无法通过这种方式完成此操作:如何从我的react应用程序将对象附加到节点api req.body ?

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

推荐答案

如果您想传递字符串serach标记,为什么要按照 rest 传递在 body 中传递它像这样

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',
      },
     ),
    })
  }

这篇关于在GET请求中传递有效负载React Fetch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆