how to handle post data in client on express - node.js

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']
})

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

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

Can't POST (and parse) params to app.post() in express.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.

node express upload file with mean stack

I should implement an upload form
I thought of using bodyparser but I read
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
so what's the way to upload a file with express using the mean stack ?
may be formidable or other modules ?
That warning is specifically against adding the express.bodyparser middleware to your entire stack as it adds express.multipart to all POST endpoints and therefore file uploads are automatically accepted at all POST endpoints. By default the framework automatically saves any uploaded files to /tmp and so unless you are cleaning them up an attacker could flood your disk with uploaded files.
If you want to avoid using additional modules, what you should do is implement express.multipart on the endpoint(s) where you want to allow file uploads. Here's what I'm talking about:
var express = require("express")
, app = express();
// middleware (no bodyparser here)
app.use(express.json());
app.use(express.urlencoded());
// average GET endpoint
app.get("/", function(req,res) {
res.send('ok');
});
// average POST endpont
app.post("/login", function(req,res) {
res.send('ok');
});
// File upload POST endpoint
app.post('/upload', express.multipart, function(req, res) {
//File upload logic here
//Make sure to delete or move the file accordingly here, otherwise files will pile up in `/tmp`
});
Note the inclusion of express.multipart in the file upload endpoint. This endpoint will now process multipart file uploads, and assuming you handle them correctly they won't be a threat.
Now, having told you all of this, Connect is moving to deprecate multipart due to this exact issue, but there don't seem to be any plans to add a stream based file upload replacement. What they instead recommend is that you use node-multiparty which uses streams to avoid ever placing a file on disk. However, there don't seem to be any good references I can find for using multiparty as a middleware without saving files though, so you'll have to contact the author of multiparty or take a closer look at the API for implementing it with Express.
I created an example that uses Express & Multer - very simple, avoids all Connect warnings
https://github.com/jonjenkins/express-upload

Node.js express correct use of bodyParser middleware

I am new to node.js and express and have been experimenting with them for a while. Now I am confused with the design of the express framework related to parsing the request body.
From the official guide of express:
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
After setting up all the middleware, then we add the route that we want to handle:
app.post('/test', function(req, res){
//do something with req.body
});
The problem with this approach is that all request body will be parsed first before the route validity is checked. It seems very inefficient to parse the body of invalid requests. And even more, if we enable the upload processing:
app.use(express.bodyParser({uploadDir: '/temp_dir'}));
Any client can bombard the server by uploading any files (by sending request to ANY route/path!!), all which will be processed and kept in the '/temp_dir'. I can't believe that this default method is being widely promoted!
We can of course use the bodyParser function when defining the route:
app.post('/test1', bodyParser, routeHandler1);
app.post('/test2', bodyParser, routeHandler2);
or even perhaps parse the body in each function that handle the route. However, this is tedious to do.
Is there any better way to use express.bodyParser for all valid (defined) routes only, and to use the file upload handling capability only on selected routes, without having a lot of code repetitions?
Your second method is fine. Remember you can also pass arrays of middleware functions to app.post, app.get and friends. So you can define an array called uploadMiddleware with your things that handle POST bodies, uploads, etc, and use that.
app.post('/test1', uploadMiddleware, routeHandler1);
The examples are for beginners. Beginner code to help you get the damn thing working on day 1 and production code that is efficient and secure are often very different. You make a certainly valid point about not accepting uploads to arbitrary paths. As to parsing all request bodies being 'very inefficient', that depends on the ratio of invalid/attack POST requests to legitimate requests that are sent to your application. The average background radiation of attack probe requests is probably not enough to worry about until your site starts to get popular.
Also here's a blog post with further details of the security considerations of bodyParser.

Resources