fetch() POST request to Express.js generates empty body {}(fetch() 对 Express.js 的 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.
希望对您有所帮助!
这篇关于fetch() 对 Express.js 的 POST 请求生成空正文 {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:fetch() 对 Express.js 的 POST 请求生成空正文 {}
				
        
 
            
        - 失败的 Canvas 360 jquery 插件 2022-01-01
 - Flexslider 箭头未正确显示 2022-01-01
 - addEventListener 在 IE 11 中不起作用 2022-01-01
 - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - 400或500级别的HTTP响应 2022-01-01
 - Fetch API 如何获取响应体? 2022-01-01
 
						
						
						
						
						