首页 > 解决方案 > 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"

笔记:

  1. 我也尝试在 fetch() 中发送正文,body: JSON.stringify({"Data": "MY DATA"})但得到相同的空 {}
  2. 我的 fetch() 请求或 bodyParser() 设置不正确。

标签: javascriptexpressfetchbody-parser

解决方案


除了之前的当前 bodyParser app.use() 之外,添加以下行:

app.use(bodyParser.json());

这将使bodyParser能够解析application/json.

希望这会有所帮助!


推荐阅读