gpt4 book ai didi

javascript - 来自 ReactJs 的 POST 请求

转载 作者:太空宇宙 更新时间:2023-11-03 23:11:42 27 4
gpt4 key购买 nike

我想使用ReactJs接收来自前端的post请求。 api 正在工作,我收到一个 get 请求,我的 React 组件也正在工作。这是我来自 React 组件的发布请求:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function submitBtn() {

return (
fetch("api", {
method: "POST",
headers : {
'Content-Type':'application/json',
'Accept':'application/json'
},
body: JSON.stringify('my data')
}).then(res => {
console.log("Request complete! response:", res);
})
)
}
return (
<div>
<input ref={nameRef} type='text' placeholder='name' name='firstName' />
<input ref={lastnameRef} type='text' placeholder='last name' name='lastName' />
<button onClick={submitBtn} type='submit'>Fetch</button>
</div>
)
...</code></pre>
</div>
</div>

以下是我的 NodeJs 代码:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> app.post('/api', function (req, res) {
console.log("Got a POST request");
res.json({ username: req.body.firstName, lastname: req.body.lastName });
res.sendStatus(200);
})</code></pre>
</div>
</div>

另外,我使用了 bodyParser。问题是我无法从我的发布请求中接收数据?可能是什么问题?我还遇到了问题:Unexpected token "in JSON atposition 0。在我的情况下这可能是什么?

最佳答案

您的 JSON 不正确。发送 fetch 请求正文时必须是字符串化的 JSON。

function submitBtn() {

return (
fetch("api", {
method: "POST",
headers : {
'Content-Type':'application/json',
'Accept':'application/json'
},
body: JSON.stringify({firstName: "toto", lastName: "momo"})
}).then(res => {
console.log("Request complete! response:", res);
})
)
}
return (
<div>
<input ref={nameRef} type='text' placeholder='name' name='firstName' />
<input ref={lastnameRef} type='text' placeholder='last name' name='lastName' />
<button onClick={submitBtn} type='submit'>Fetch</button>
</div>
)
...

这是一个示例:https://googlechrome.github.io/samples/fetch-api/fetch-post.html

关于javascript - 来自 ReactJs 的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60415749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com