如何使用 JavaScript 将表单数据发送到服务器
How to send form data to the server with JavaScript
我正在使用两台服务器,一台用于 React(位于地址 http://localhost:3000/contact
),另一台用于 Express(位于地址 http://localhost:5000/
)。我想通过一些 HTTP 请求方法作为 POST 方法发送表单数据对象,但我在 "backend" 端得到空对象。
我有一个带有 onSubmit
事件的简单表单,它首先创建一个具有表单数据值的对象:
const data = {
firstInput: evt.target.elements.firstInput.value,
secondInput: evt.target.elements.secondInput.value
}
注意:我测试了如果使用 DevTools 和 React Dev 工具获取所有数据直到这里,直到这里它工作得很好。
第二个带有 Express 的服务器只有一个简单的端点,它应该接收此数据或至少打印我在 req.body
对象中发送的内容:
server.post("/", (req, res) => {
res.end(req.body);
});
注意 2: 还测试了这个端点并且它工作正常但是 req.body
得到一个空对象。
我测试了几种方法,例如:
Native 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);
});
Error:
此外,在 fetch API
上尝试使用 async
/ await
方法,但我不确定是否在 React 组件上使用它。
我也试过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}
});
我正在使用两台服务器,一台用于 React(位于地址 http://localhost:3000/contact
),另一台用于 Express(位于地址 http://localhost:5000/
)。我想通过一些 HTTP 请求方法作为 POST 方法发送表单数据对象,但我在 "backend" 端得到空对象。
我有一个带有 onSubmit
事件的简单表单,它首先创建一个具有表单数据值的对象:
const data = {
firstInput: evt.target.elements.firstInput.value,
secondInput: evt.target.elements.secondInput.value
}
注意:我测试了如果使用 DevTools 和 React Dev 工具获取所有数据直到这里,直到这里它工作得很好。
第二个带有 Express 的服务器只有一个简单的端点,它应该接收此数据或至少打印我在 req.body
对象中发送的内容:
server.post("/", (req, res) => {
res.end(req.body);
});
注意 2: 还测试了这个端点并且它工作正常但是 req.body
得到一个空对象。
我测试了几种方法,例如:
Native
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); });
Error:
此外,在 fetch API
上尝试使用 async
/ await
方法,但我不确定是否在 React 组件上使用它。
我也试过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}
});