為什么代碼輸出空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);
uj5u.com熱心網友回復:
您的fetch陳述句使用 POST 請求Content-Type: text/html,這是非常不尋常的。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);
});
uj5u.com熱心網友回復:
**Just add the express.urlencoded({extended: true}) also use the express.json**
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); //empty here //{}
res.send(req.body);
});
app.listen(3000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475473.html
標籤:表示
