Route Data in Express.js
This article gives you info about how to access the data in Express server, which is sent from the client. Read on to learn more.
Join the DZone community and get the full member experience.
Join For FreeExpress is an amazing server side framework built on the Node.js platform. It is a matured and well-maintained framework in the Node.js community. Its main focus is to build Web applications and REST API using the Node.js platform.
With web application and REST API, we often pass the data from client to server in various forms, such as query parameter or URL parameter in the case of GET requests and post body, file, or multi-part data in the case of POST or PUT requests.
In this article, you will see various ways to get data sent from client in the Express server route handler.
The following are various ways:
- Query parameter
- URL parameters
- Header data
- Post body data
- File multi-part data
In this article, I assume you have written a basic express app which has handlers/middlewares for routes. If not, refer to this article and this one.
Further, all the data which is sent from the client will be available in the request (shortened as req) object inside route handlers. Further, it will be available in the various properties of the request object.
Query Parameters
For starters, query parameters are those which are passed in URI after "?" sign and those are separated by the "&" symbol. In Express.js, Query parameters can be fetched:
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 the above query parameter, we can use:
req.query.name , req.query.age
The 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 appear as part of URL, like as follows:
/path/of/url/[name-of-param];
For example, for our API we want to fetch the details of a specific person, then we might use- as above:
/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 the following route handler:
router.get('/api/people/:username', function(req, res){
var name = req.params.username;
// rest of code
});
Note how the URL parameter is specified in the route URL. It is preceded with a colon (:) at the start, which is mandatory to put there.
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 the current Request.
Usually, HTTP headers can be standard like content-type (etc.) or custom headers like any-custom-header (etc.). Accessing both are the same:
req.headers.<name-of-header> or
req.headers.['name-of-header-which-is-separated-by-hypen']
For example, accessing HTTP headers:
req.headers['content-type']
req.headers['content-encoding']
req.headers.my_header
Post Data
This will be sent from the POST request from the client. The content type of the data can be anything like file, JSON object, form-url-encoded, or raw data.
To fetch this data on server side, you will find the following few steps:
- Add body-parser module to project
- Require body-parser and set it as middleware to extract the POST data
- Now, once the request is made on URL, it will be available in request.body object
Adding body-parser Module to Project
While creating a project from express-generator, this usually gets added by default. But, if by chance it is not in the project, add it via the 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 the body parser module is configured, we can access POST data from the req.body object.
For example, 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 the 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 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 the complexity in handling it the same and keeping body-parser simple.
There are a few modules out there in the 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 the above code, we required the multer module and configured it by passing the object where we specified the destination directory to which files will be get stored.
Now, let's assume the following is the HTML we are using on the 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>
The following route handler handles the uploads for the 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 the second parameter to route handler is upload.single('avatar')
, which gets the file named "avatar" from the form and stores it in the configured uploads directory. Further,it creates the file object in the req.file
object and passes it to the router handler specified next.
Now, this req.file contains the following properties which represent 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 a sample output:
{
fieldname: 'avatar',
originalname: 'ajduke.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '4b5b82420c8c3b98a9832c7705be9fd5',
path: 'uploads/4b5b82420c8c3b98a9832c7705be9fd5',
size: 141530
}
Conclusion
This article gives you info about how we can access the data in Express server, which is sent from the client.
Published at DZone with permission of Abhijeet Sutar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments