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

Pass payload in GET request React fetch(在 GET 请求中传递有效负载 React fetch)

本文介绍了在 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.

如果不能这样做:如何从我的反应应用程序将对象附加到节点 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 标签,为什么你要在 body 中传递它,就像 rest pass它在这样的网址中

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 GET 请求中传递有效负载 React fetch

基础教程推荐