Home > front end >  How to post request?
How to post request?

Time:05-16

why is the code outputting an empty 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);

CodePudding user response:

Your fetch statement makes a POST request with Content-Type: text/html, which is highly unusual. express.urlencoded() does not fill req.body for this content type, it is only meant for Content-Type: application/x-www-form-urlencoded.

You can parse arbitrary textual content with code like this:

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

CodePudding user response:

**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);
  • Related