[英]Post request from ReactJs
我想使用 ReactJs 从前端接收发布请求。 api 正在工作,我收到了一个 get 请求,我的 React 组件也在工作。 这是我来自 React 组件的 post 请求:
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>
)
...
波纹管是我的 NodeJs 代码:
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);
})
另外,我使用了bodyParser。 问题是我无法从我的发布请求中接收数据? 可能是什么问题? 我也遇到了这个问题: Unexpected token " in JSON at position 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
请记住以下几点:
使用fetch时,正文数据应针对"Content-Type": "application/json"
进行字符串化:
body: JSON.stringify(object)
res.json({ username: req.body.firstName, lastname: req.body.lastName });
将自动将状态设置为 200 并结束req-res
循环。 所以调用res.sendSatatus()
会抛出错误,因为req-res
循环已经结束。
如果您想通过数据使用手动设置状态
res.status('statusCode').json(object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.