简体   繁体   English

对Express.js的fetch()POST请求生成空主体{}

[英]fetch() POST request to Express.js generates empty body {}

Goal: send some defined string data from HTML in a fetch() function eg "MY DATA" 目标:通过fetch()函数从HTML发送一些定义的字符串数据,例如“ MY DATA”


My code: 我的代码:

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 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);
});

Currently: console.log(req.body) logs {} 当前: console.log(req.body)记录{}

Desired: console.log(req.body) logs "MY DATA" 需要: console.log(req.body)记录"MY DATA"

NOTES: 笔记:

  1. I also tried sending body in fetch() as body: JSON.stringify({"Data": "MY DATA"}) but get the same empty {} 我还尝试将fetch()中的body: JSON.stringify({"Data": "MY DATA"})作为body: JSON.stringify({"Data": "MY DATA"})发送body: JSON.stringify({"Data": "MY DATA"})但得到相同的空{}
  2. I either my fetch() request, or my bodyParser(), is not setup correctly. 我的fetch()请求或bodyParser()设置不正确。

Add the following line in addition to your current bodyParser app.use() right before: 在当前的bodyParser app.use()之前添加以下行:

app.use(bodyParser.json());

This will enable bodyParser to parse content type of application/json . 这将使bodyParser能够解析application/json内容类型。

Hopefully that helps! 希望有帮助!

I feel a bit stupid now once I worked out what bodyParser.urlencoded (source: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions ) 一旦我确定了bodyParser.urlencoded我现在就感到有点愚蠢(来源: https : bodyParser.urlencoded

Returns middleware that only parses urlencoded bodies 返回仅解析urlencoded主体的中间件

Solution

Changed the fetch() request, from: 从以下位置更改了fetch()请求:

body: "MY DATA",
headers: { "Content-Type": "application/json" }

to

body: JSON.stringify({"Data": "MY DATA"}),
headers: { "Content-Type": "application/x-www-form-urlencoded" }

which solved the problem! 解决了问题! Console logged: 控制台已记录:

{ '{"Data":"MY DATA"}': '' } {'{“数据”:“我的数据”}':''}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM