javascript - 使用 fetch 将跨域 JSON 数据发布到 Express 后端
问题描述
我正在尝试使用 Fetch 从表单中发布一些 JSON 数据并记录来自 Express 服务器的响应,这应该是包含发布的表单值的简单 JSON 响应,但我只在控制台中接收到一个空对象。
HTML 和 JavaScript 可以从此JSFiddle Link执行。
如何从服务器接收填充的 JSON 对象响应?
HTML
<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。
解决方案
你不能POST
是一个普通的 javascript 对象。
但是,请务必检查RFC 1341Content-type
中定义的所有可能值以及mime 类型列表。
根据 MDN
试试这个代码。
const form = document.getElementById("myForm");
form.addEventListener("submit", (e) => {
e.preventDefault();
var data = {
firstName: e.target.firstName.value,
lastName: e.target.lastName.value
}
fetch("http://localhost:5000/form-post", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify(data)
})
.then((res) => res.json())
.then((data) => console.log(data));
});
推荐阅读
- php - 去掉body PSR-7 Slim3中间件?
- ruby-on-rails - 如何在 Rails 中查看用户的所有订单?
- c - C - 为什么只有第二个命令有效?
- python - 有没有办法打印列表中类的所有特定元素?
- php - 一个网页可以显示多少张照片
- selenium - 创建一个测试 Web 应用程序重放以测试并预热服务器
- docker - Docker错误:无法启动服务...:找不到网络7808732465bd529e6f20e4071115218b2826f198f8cb10c3899de527c3b637e6
- javascript - 使用 querySelectorAll 查找与逗号分隔的属性的匹配项
- windows - 是否可以使用登录的 Windows 用户凭据对 Web API 进行身份验证?
- python - 谷歌 colab TPU 和在训练时从光盘读取