【发布时间】:2018-10-07 00:07:31
【问题描述】:
目标: 在 fetch() 函数中从 HTML 发送一些已定义的字符串数据,例如“我的数据”
我的代码:
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() 设置不正确。
【问题讨论】:
标签: javascript express fetch-api body-parser