Use ExpressJS to Get URL and POST Parameters

Often when we are building applications using ExpressJS, we will need to get information from our users.

This can happen any number of ways but the two most popular are:

URL Parameters

These are information that are passed through the URL like so:

http://example.com/api/users?id=4&token=sdfa3&geo=us

This is most seen in requesting information from an API.

URL Parameters are grabbed using req.param.variable_name

POST Parameters

These are information that come from forms. We’ll be grabbing from forms that pass information as application/x-www-form-urlencoded.

POST Parameters are grabbed using req.body.variable_name

Let’s take a look at how we can grab the parameters using the popular Node.js framework, ExpressJS.

Sample App to Test

We’ll be creating a sample application to make sure that grabbing parameters works. We’ll also be using POSTman to test the form POST.

We’ll only need two files:

- package.json
- server.js

Here is the package.json

{
  "name": "express-parameters",
  "main": "server.js",
  "dependencies": {
    "express": "~4.10.2"
  }
}

Here’s the start of our server.js:

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

We can now start our server using:

$ node server.js

You can also use nodemon server.js if you have nodemon installed so that the server will restart on changes.

Now let’s create two routes now to test grabbing parameters.

Getting Any URL Parameter

For this example, we’ll grab a parameter directly from the URL. Let’s say we are using the example URL: http://example.com/api/users?id=4&token=sdfa3&geo=us

The parameters that come out of this will be:

id 4
token sdfa3
geo us

It’s very easy to grab these parameters. Here’s the route and the method for grabbing parameters is req.param().

// routes will go here
app.get('/api/users', function(req, res) {
  var user_id = req.param('id');
  var token = req.param('token');
  var geo = req.param('geo');  

  res.send(user_id + ' ' + token + ' ' + geo);
});

The parameters are naturally passed through the req (request) part. Now if we go to our browser at http://localhost:8080/api/users?id=4&token=sdfa3&geo=us, we’ll be able to see the three parameters!

Specific Routing for Specific Parameters

We can also name the paramter directly in the route itself. Here’s a URL and example:

// http://localhost:8080/api/1
  app.get('/api/:version', function(req, res) {
    res.send(req.params.version);
  });

Route Parameter Middleware

Next up, we’ll be using the Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations (like checking if a user exists) or grabbing important information about that user or item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('name', function(req, res, next, name) {

    // check if the user with that name exists
    // do some validations
    // add -dude to the name
    var modified = name + '-dude';

    // save name to the request
    req.name = modified;

    next();
});

// http://localhost:8080/api/users/chris
app.get('/api/users/:name', function(req, res) {
    // the user was found and is available in req.user
    res.send('What is up ' + req.name + '!');
});

If we visit the URL in our browser, we’ll see:

What is up chris-dude!

Pretty neat. You can use this param middleware for validations and making sure that information passed through is valid and the correct format.

We then save information to the request (req) so that our other route will have access to it.

Further Reading More Express routing: Learn to Use the Express 4.0 Router

POST Parameters

To get POST parameters, we’ll need two the ExpressJS body-parser package. This will allow us to grab information from the POST.

Install body-parser

We’ll need to install body-parser using:

$ npm install body-parser --save

Now that we have that package and it has been added to our package.json thanks to the --save modifier, we have to configure it in our server.js file.

Add the following after you define the app variable.

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

With body-parser configured, we can now create our route:

We will grab POST parameters using req.body.variable_name

// POST http://localhost:8080/api/users
// parameters sent with 
app.post('/api/users', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

We can test this using POSTman and send information as application/x-www-form-urlencoded:

2014-11-14

Conclusion

Those are the quick ways we can grab information using ExpressJS. Grabbing data from the request is an easy enough process.

Just grab the information quick and easily so that you can move on to building great things!

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.