Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 941
Jay Bhajiyawala Avatar asked Mar 27 '26 09:03

Jay Bhajiyawala


2 Answers

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.

like image 52
taipei Avatar answered Mar 28 '26 23:03

taipei


if you are using multer as middleware on the post route with other middle middlewares put the multer middleware first.

app.post(
    "/api/private/buyer/add-buyer",
    [
        upload, verifySignUp.checkDuplicateUsernameOrEmail,
    ],
    controller.createBuyer
);

here upload is multer middleware I put it first it works for me.

like image 28
umair ihsan Avatar answered Mar 28 '26 21:03

umair ihsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!