对Express.js的fetch()POST请求生成空主体{} [英] fetch() POST request to Express.js generates empty body {}
本文介绍了对Express.js的fetch()POST请求生成空主体{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标:在fetch()
函数中从 HTML 发送一些已定义的字符串数据. 我的数据"
Goal: send some defined string data from HTML in a fetch()
function e.g. "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>
Server.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()设置不正确.
- I also tried sending body in fetch() as
body: JSON.stringify({"Data": "MY DATA"})
but get the same empty {} - I either my fetch() request, or my bodyParser(), is not setup correctly.
推荐答案
在当前的bodyParser app.use()之前添加以下行:
Add the following line in addition to your current bodyParser app.use() right before:
app.use(bodyParser.json());
这将使 bodyParser 能够解析内容类型application/json
.
This will enable bodyParser to parse content type of application/json
.
希望有帮助!
这篇关于对Express.js的fetch()POST请求生成空主体{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文