javascript - 如何使用 JavaScript 将表单数据发送到服务器
问题描述
我正在使用两台服务器,一台用于React(在 address 上http://localhost:3000/contact
),另一台用于Express(在 address 上http://localhost:5000/
)。我想通过一些 HTTP 请求方法作为 POST 方法发送表单数据对象,但我在“后端”端得到空对象。
我有一个带有onSubmit
事件的简单表单,它首先使用表单数据值创建一个对象:
const data = {
firstInput: evt.target.elements.firstInput.value,
secondInput: evt.target.elements.secondInput.value
}
注意:我使用 DevTools 和 React Dev 工具测试了 If get all data until here,直到这里它工作得很好。
第二个使用 Express 的服务器只有一个简单的端点,它应该接收这些数据或至少打印我在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
但我不确定是否在 React 组件上使用它。
我也尝试过http API,但我得到了相同的结果。
我想我的第一个问题是如何将格式正确的数据从组件端发送到服务器端。不管怎么说,还是要谢谢你。
解决方案
使用这个包查询字符串 你可以像这样使用:
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}
});
推荐阅读
- python - 数据框中python的“for循环”,我可以加快速度吗?
- python - 如何在不创建新列的情况下更新列值?
- android - Android Firebase 列表适配器构造函数错误
- php - PHP中的动态类使用
- jboss - Jboss Fuse ESB 6.3 上的 Appdynamics Instrumentation
- model - 在 gensim 包装器中访问模型
- php - 在 CodeIgniter 中通过 jQuery AJAX 插入和移动多个图像
- ios - 在 iOS SDK 的 App Modules 中添加框架
- php - 如何使用 PHP 在我所有来自 mysql 的帖子中获得最受欢迎的帖子
- arrays - swift中连续数组的数据结构