我尝试使用Fetch从表单中发布一些JSON数据,并记录来自Express服务器的响应,这应该是一个包含发布的表单值的简单JSON响应,但我在控制台中只接收到一个空对象。
JSFiddle Link
.
如何从服务器接收填充的JSON对象响应?
<form id="myForm">
<input type="text" placeholder="Enter First Name" name="firstName" />
<input type="text" placeholder="Enter Last Name" name="lastName" />
<input type="submit" value="SUBMIT" />
</form>
JavaScript语言
const form = document.getElementById("myForm");
form.addEventListener("submit", (e) => {
e.preventDefault();
fetch("http://localhost:5000/form-post", {
method: "POST",
mode: "cors",
body: {
firstName: e.target.firstName.value,
lastName: e.target.lastName.value
}
})
.then((res) => res.json())
.then((data) => console.log(data));
});
const express = require("express");
const app = express();
const cors = (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, Content-Type");
next();
};
app.use(cors);
app.use(express.json());
app.post("/form-post", (req, res) => {
res
.status(200)
.json({
First_Name: req.body.firstName,
Last_Name: req.body.lastName
});
});
app.listen(5000, () => console.log("Server started on port 5000..."));
[编辑:]
它在Postman(附屏幕截图)中运行良好,但在Fetch中似乎不起作用。