我有两台服务器,一个阵营(在地址http://localhost:3000/contact
),另一个是快速(在地址http://localhost:5000/
)工作。我想通过一些HTTP请求方法为POST方法发送表单数据的对象,但我得到了“后端”侧空对象。
我有一个简单的形式与首先创建与表格数据值的对象的事件onSubmit
:
const data = {
firstInput: evt.target.elements.firstInput.value,
secondInput: evt.target.elements.secondInput.value
}
注:我测试如果得到的所有数据,直到这里DevTools和应对开发工具,直至在这里它的伟大工程。
而随着快递第二服务器只需要一个简单的端点应当接收该数据或至少打印我在req.body
对象发送:
server.post("/", (req, res) => {
res.end(req.body);
});
注2:还测试了这款端点,它工作正常,但req.body
得到一个空对象。
我已经测试了几种方法,如:
本地
fetch
API:fetch("http://localhost:5000/", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }).then(res => { console.log(res); });
错误:
此外,试图与async
await
/ fetch API
的做法,但我不知道如何使用它作出反应的组成部分。
我也试过http API但我同样得到了。
我想我的第一个问题是如何正确地发送从组件侧到服务器端的格式化数据。不管怎么说,还是要谢谢你。
使用这个包query-string你可以使用这样的:
import queryString from 'query-string';
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important
body: queryString.stringify({for:'bar', blah:1}
});