如何post请求?

How to post request?

为什么代码输出一个空的req.body

const express = require("express");
const app = express();

app.use(express.urlencoded());

app.get("/", (req, res, next) => {
  res.send(`<script>
    fetch("/push", {
        body: "someText",
        headers: {
            "Content-Type": "text/html; charset=UTF-8",
        },
        method: "POST",
    }).then((data) => console.log(data));
</script>`);
});

app.post("/push", function (req, res, next) {
  console.log(req.body); //empty here //{}
  res.send(req.body);
});

app.listen(3000);

只需添加 express.urlencoded({ extended: true }) 也可使用 express.js

const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json())

app.get("/", (req, res, next) => {
  res.send(`<script>
    fetch("/push", {
      body: "someText",
      headers: {
        "Content-Type": "text/html; charset=UTF-8",
      },
      method: "POST",
    }).then((data) => console.log(data));
  </script>`);
});

app.post("/push", function (req, res, next) {
  console.log(req.body);
  res.send(req.body);
});

app.listen(3000);

您的 fetch 语句使用 Content-Type: text/html 发出 POST 请求,这是非常不寻常的。 express.urlencoded() 不会为这种内容类型填充 req.body,它仅适用于 Content-Type: application/x-www-form-urlencoded

您可以使用如下代码解析任意文本内容:

var body = "";
req.on('data', function(chunk) {
  body += chunk.toString();
})
.on('end', function() {
  res.send(body);
});