Pass payload in GET request 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
基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
