Home > OS >  Node.js req.body undefined in form-data content-type
Node.js req.body undefined in form-data content-type

Time:03-28

Here I have created the small demo for this form-data passing API. Now I'm checking this API using postman but I'm not getting any data.

Code

const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(
  bodyParser.json({
    limit: "50mb"
  })
);

app.use(
  bodyParser.urlencoded({
    limit: "50mb",
    extended: true
  })
);

app.post('/form-data', (req, res) => {
  console.log("form-data ->> ", req.body) 
});

server = http.createServer(app);

server.listen(4000[![enter image description here][1]][1], () => {
  console.log(`Server started`);
});

Server log

Server started
form-data ->> {}

enter image description here

Header enter image description here

enter image description here

CodePudding user response:

I tried to reproduce your code with small changes.

const express = require("express");
const bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();

const app = express();

// for parsing application/json
app.use(
    bodyParser.json({
        limit: "50mb",
    })
);
// for parsing application/xwww-form-urlencoded
app.use(
    bodyParser.urlencoded({
        limit: "50mb",
        extended: true,
    })
);

// for parsing multipart/form-data
app.use(upload.array());

app.post("/form-data", (req, res) => {
    console.log(`\nform-data ->> ${JSON.stringify(req.body)}`);
    res.send(req.body);
});

const port = 3000;
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

I removed your server initialization since we can use app listen directly from the expressjs.

And I can send post with "form-data", "x-www-form-urlencoded", or "raw" successfully.

You might double-check on which tutorial you following. Since express documentation is clear enough.

*Edited I added multer to parsing the form-data.

  • Related