Express is amazing server side framework built on Node.js platform. It is matured and well maintained framework in Node.js community. Its main focus is to build Web applications and REST API using Node.js platform.
With Web application and REST API, we often pass the data from client to server in various form such as query parameter or url parameter in case of GET request and post body or file or multi-part data in case of POST or PUT requests.
In this article, you will see various ways to get these data sent from client in Express server route handler.
Following are various ways-
- Query parameter
- URL parameters
- Header data
- Post body data
- File multi-part data
In this article, I assume you had written basic express app which has handlers/middlewares for routes. If not refer this article and this one.
Further all the data, which is sent from client will be available in the request ( shortened as req) object inside route handlers. Further it will be available in the various properties of request object.
Query parameters
For starters, query parameters are those which are passed in URI after ‘?’ sign and those are separated by the ‘&’
In Express.js, Query parameters can be fetched from the
req.query.<name-of-query-parameter>
It is the map object which contains the all query parameter for given URL.
So, for URL –
GET /api/people?name=ajduke&age=20
To get above query parameter , we can use ,
req.query.name , req.query.age
Actual route handler will look this,
router.get('/api/people', function(req, res){ var name = req.query.name; var age= req.query.age; // rest of handler function })
URL Parameters
URL parameters are those which appears as part of URL, like as follows –
/path/of/url/[name-of-param];
for. e.g, for our API, we want to fetch the details of specific person, then we might use- as above
GET /api/people/ajduke
To use fetch this URL parameter in route handler, we can use req.params object, which contains all the URL parameters.Like,
req.params.<name-of-param>
In our example, we can have following route handler-
router.get('/api/people/:username', function(req, res){ var name = req.params.username; // rest of code });
Note that, how it URL parameter is specified in the route URL. It is preceded with colon (:) at start. It is mandatory to put it.
Header data
To access the HTTP Headers, they are available via req.headers object. It contains the map of all the headers which are passed for current Request.
Usually, HTTP headers can be standard like content-type etc. or custom headers like any-custom-header etc. Accessing both are same as
req.headers.<name-of-header> or req.headers.['name-of-header-which-is-separated-by-hypen']
For e.g, accessing HTTP headers-
req.headers['content-type'] req.headers['content-encoding'] req.headers.my_header
Post data
This will be sent from POST request from the client. The content type of data can be anything like file, JSON object, form-url-encoded, raw data.
To fetch this data on server side, you will find following few steps
- Add body-parser module to project
- require body-parser and set it as middleware to extract the POST data
- now, once request is made on URL, it will be available in request.body object
Adding body-parser module to project
While creating project from express-generator, this is usually get added by default, but if anychance, it is not in project, add it via following command-
npm i -S body-parser
require body parser module and configure
var app = express(); // require body parser module var bodyParser = require('body-parser'); // set init body parser and set it as the middleware for the express app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
Access the POST data
Once body parser module is configured, we can access POST data from the req.body object
For e.g. For the request, you are passing Post data as
POST /api/people/ -- POST data goes here --- name=ajduke age=21 -- POST data ends here---
Inside, any handler, you can access it via following-
var name= req.body.name; var age = req.body.age;
Multi-part form data
This multi part form data is usually used to send the the Files. Basically, file upload scenario.
In Express, handling Post data is managed by the body-parser module,which we saw earlier. But this module does not handle the multi-part form data. Due to complexity in handling same and keeping body-parser simple.
There are few modules out there in npm repository for handling multi-part data but for this post we going to use multer npm module.
First you will need to configure this module to handle the file uploads in our Express app.
var multer = require('multer'); var upload = multer({ dest: 'user_avatars/' }); // rest of the code
In above code, we require‘d the multer module and configured it by passing object where we specified the destination directory to which files will be get stored.
Now, lets assume following is the html we are using on client side for uploads-
<form action="/user/profile" enctype="multipart/form-data" method="post"> <input name="username" type="text" /> <input name="avatar" type="file" /> <input type="submit" /> </form>
Following route handler, handles the uploads for file
app.post('/user/profile', upload.single('avatar'), function (req, res, next) { // req.file contains the object which represents the avatar file console.log(req.file) })
Note that, second parameter to route handler is upload.single('avatar')
, which does gets the file named ‘avatar’ from form and stores it in configured uploads directory.Further,it creates the file object in the req.file
object and pass it to router handler specified next.
Now, this req.file contains the following properties which represents the file
fieldname– field name specified in form
originalname- name of file on user computer
encoding- encoding type of the file
mimetype- MIME type of the file
size- actual size of the file (specified in bytes)
filename: actual file name which is stored on the disk
path: files path on disk
destination: destination directory to which all files are uploaded
Following is sample output –
{ fieldname: 'avatar', originalname: 'ajduke.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: 'uploads/', filename: '4b5b82420c8c3b98a9832c7705be9fd5', path: 'uploads/4b5b82420c8c3b98a9832c7705be9fd5', size: 141530 }
This article gives you info about how we can access the data in Express server, which is sent from client . Following is the recap
- Query parameter- req.query.<name-of-param>
- URL parameter- req.query.<name-of-param>
- Header data- req.query.<name-of-header>
- POST data- configure-body parser then it will be available as req.body.<name-of-param>
- Multi-part data- Configure multer module, data will be available in the req.file
Leave a Reply