javascript - fetch() 对 Express.js 的 POST 请求生成空正文 {}
问题描述
目标:在函数中从HTML发送一些定义的字符串数据,fetch()
例如“MY DATA”
我的代码:
HTML
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function fetcher() {
fetch('/compute',
{
method: "POST",
body: "MY DATA",
headers: {
"Content-Type": "application/json"
}
}
)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
</script>
</body>
</html>
服务器.js
var express = require("express");
var app = express();
var compute = require("./compute");
var bodyParser = require("body-parser");
//not sure what "extended: false" is for
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/compute', (req, res, next) => {
console.log(req.body);
var result = compute.myfunction(req.body);
res.status(200).json(result);
});
当前: console.log(req.body)
日志{}
所需: console.log(req.body)
日志"MY DATA"
笔记:
- 我也尝试在 fetch() 中发送正文,
body: JSON.stringify({"Data": "MY DATA"})
但得到相同的空 {} - 我的 fetch() 请求或 bodyParser() 设置不正确。
解决方案
除了之前的当前 bodyParser app.use() 之外,添加以下行:
app.use(bodyParser.json());
这将使bodyParser能够解析application/json
.
希望这会有所帮助!
推荐阅读
- macos - 具有图形模式的可调整大小的 NSDatePicker
- python - 从网页中提取链接
- android - 除非执行 mSettingsClient.checkLocationSettings,否则无法获取 locationSettings 的 getStatusCode
- .htaccess - 如何使用 htacces 从 URL 中删除锚点(“#”)?
- c - 在 C 中重铸一个数组
- vb.net - 插入查询前的验证
- sql - SQL 列未找到问题
- python - 使用 BeautifulSoup 从带有相关标签的网页中提取所有图像链接
- c# - 从字典中正确地将字符串转换为 Json
- python - 基于相似短语生成自然语言