Can't POST (and parse) params to app.post() in express.js - node.js

I checked this question but for some reasons the solution given is not working for me. In my express.js I have:
...
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
...
Run test using POSTman
app.post('/upload', function(req, res) {
console.log(req.body) // undefined
console.log(req.params) // undefined
})
and the result:
So both body & params are empty. Any suggestions?

The reason the solution in the link you provided doesn't work is because that version of body-parser is out of date and doesn't include form-data parsing anymore (and it used to be bundled with express).
With that being said, based on your screenshot, it looks like you are sending data of type multipart/form-data(you can check this in the request headers) to your server and your code sample only shows middleware that handles urlencoded and json data types.
You need to add middleware that handles that data type. The latest body parser says (https://github.com/expressjs/body-parser):
This does not handle multipart bodies, due to their complex and
typically large nature. For multipart bodies, you may be interested in
the following modules:
busboy and connect-busboy
multiparty and connect-multiparty
formidable
multer
So check out one of the above parsers. I use busboy and it works great.

Related

multipart/form-data returns empty object | Nodejs

Form with POST method and enctype="multipart/form-data" returns empty object in Nodejs Express.
In app.js I have used:
const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
While using only POST type and action in the <form> tag
req.body gives output in json smoothly and have no issues.
But using enctype="multipart/form-data" in express req.body returns { } - empty object
Can anyone help with this?
The urlencoded middleware only handles the application/x-www-form-urlencoded content type and json handles the application/json content type. If you specifically need to use multipart/form-data (e.g. if you need to handle file uploads), you'll need a package for that, since as of writing, express doesn't come with a multipart parser out of the box. Common packages used to handle multipart are multer and formidable.
Alternatively, if you don't need to upload files or other binary content, just remove the enctype attribute as <form> defaults to application/x-www-form-urlencoded.
incase your using multer, its possible that your calling the upload method last, please call the upload that checks for image and then the other data from the form can later be submitted
i will give an example of my route
router.post('/add-product',productController.isUserAllowed,upload.single('avatar'), productController.add_product);
so initally i was calling productController.add_product beforeupload.single('avatar'), and it didnt work, till i started with the upload that checked the image , then the add_product

When using Put Method in a Express JS Api , Do I need to use body parser?

In the code snippet below, do I need to use the urlencodedParser like I do in Post methods.
app.put('/api/provider/:id', urlencodedParser, function (req, res) {
}
body-parser parses the body of the request into req.body, which you'll likely need for your put middleware. body-parser now comes built into Express (as of v4.16.0 - below assumes you have an updated version).
The easiest implementation is to use express.json and express.urlencoded (used in body-parser) in all requests, using app.use, so that you don't have to worry about it in your middleware. Here is how npx express-generator $APP_NAME will set it up for you:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
NOTE: You'll need to set extended to true if you are expecting nested objects in your requests.

In new express where body-parser is implicit, how to get raw request body in middleware?

I would like to get the raw request body in one of my middlewares in my Express app. There are a few posts on Stackoverflow that show how to do this (e.g. Node.js - get raw request body using Express or Writing express middleware to get raw request body before body-parser), but:
They use body-parser, which I believe is built-in with the new Express version, so am not sure how to use it in this case
They extract the raw request in app.use(), which means that all routes would extract the raw request, whereas I only want to extract it in one route (more specifically, in an independent middleware that's buried deep in my code rather than in app.js, to which I want to be able to just pass the req element and extract its raw body there).
Any advice on the best way to do this?
Assuming you have not already parsed the body before reaching this route (using body-parser or something similar), following will work in your routes file:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.get('/path', bodyParser.raw(options), (req,res){
//your code
});
bodyParser.raw(options) will return a function that accepts 3 arguments (req,res,next) and the raw body will become available in req.body

how to handle post data in client on express

I am using express.js to built the website. i use .ejs as my front end and nodejs for backend i want ejs to interact with the nodejs server. I use get request and i split the url and taking the data but its no where good so i want to interact ejs file to nodejs for eg when we are using php we will try to code as $_POST['somename'] and even we do dynamic programming in php by taking the data and embedding html and writing it. i want to know to handle post request in ejs file and store the post request data and handle it throughout the file
As far as I understood you want to handle your form data, and in order to do so you have to use body-parser.
npm install body-parser
then in your app.js/server.js just add these lines
let bodyParser = require("body-parser")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
after that you will be able to get $_POST['name_here']
app.post("/whatever", (request, respone){
console.log(request.body.name_here) //same as $_POST['name_here']
})

Request Entity Too Large

My Express application is returning "Request Entity Too Large" on a file upload of only a 125kb PNG file.
I have configured the body parser middleware as such:
app.use(bodyParser.urlencoded({
limit: '5mb',
type:'*/x-www-form-urlencoded',
extended: true
}));
according to the documentation. No matter how high I set the limit, or what combination of options, I always get the same result. I am using Express 4.13.3 and body-parser 1.15.2.
What am I doing wrong?
Embarrassingly, I had accidentally pointed my route handler to the wrong Express Router instance. Once I was pointed to the correct handler, Multer picked up the multi-part POST correctly.
Interestingly, when testing with Postman, it will send an array of files, even if you only select one, which is why request.file was undefined, but request.files contained the correct value.

Resources