How to create an http server with Express in Node.js

How to create an http server with Express in Node.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

In this article you'll learn how to create a http server using Express and other basics that you need to know about it.

Requirement

Add Express as a dependency in your project, to add it use the following command in the Node.js command prompt:

npm install express

You can execute it with the --save parameter to include it in the package.json in case you have one. Now you'll be able to require the express module in your javascript files.

Structure of a HTTP server in Express

Express.js middleware

  1. HTTP method for which the middleware function applies.
  2. Path (route) for which the middleware function applies.
  3. The middleware function.
  4. Callback argument to the middleware function, called "next" by convention.
  5. HTTP response argument to the middleware function, called "res" by convention.
  6. HTTP request argument to the middleware function, called "req" by convention.

Hello world

The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs.

To create your first http server with express, create a js file with the name server.js and add the following code on it:

// Require express and create an instance of it
var express = require('express');
var app = express();

// on the request to root (localhost:3000/)
app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// On localhost:3000/welcome
app.get('/welcome', function (req, res) {
    res.send('<b>Hello</b> welcome to my http server made with express');
});

// Change the 404 message modifing the middleware
app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

// start the server in the port 3000 !
app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});

Now save the content and execute the server using the following command in your Node.js command prompt:

node server.js

Navigate to the port 3000 as previously set in the server.js file in localhost (http://localhost:3000 or http://localhost:3000/welcome) and see the magic happens.

Handle routes and request methods

For a predefined path, you can set a default request method or even all of them. Routes can be strings, patterns or regular expressions.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// 1) Add a route that answers to all request types
app.route('/article')
.get(function(req, res) {
    res.send('Get the article');
})
.post(function(req, res) {
    res.send('Add an article');
})
.put(function(req, res) {
    res.send('Update the article');
});

// 2) Use a wildcard for a route
// answers to : theANYman, thebatman, thesuperman
app.get('/the*man', function(req, res) {
    res.send('the*man');
});

// 3) Use regular expressions in routes
// responds to : batmobile, batwing, batcave, batarang
app.get(/bat/, function(req, res) {
    res.send('/bat/');
});

app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.

Handle routes with parameters

As known routing systems of know server side frameworks in other languages do, i.e Symfony, allow you to create dynamic url that expects parameters in the url (and not specifically GET parameters, but as part of the URL) to return dynamic content, Express allow you to achieve it in the same way using the "/default-url/:parameter" syntax in the url.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// route with parameters
// matches to : /books/stephenking/category/horror
app.get('/books/:user/category/:categorySlug', function(req, res) {
    console.log(req.params);
    var username = req.params.user;
    var category = req.paramas.categorySlug;
    res.send(req.params);
});

app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});

Type of response

Between the most commons task in the server side, you need to return a response to your user, Express has many methods to return a specific response according to your needs:

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

The response should be sent on every "controller" with the response object:

app.get('/', function (req, res) {
    // JSON response
    res.json({
        'myJson':'object'
    });

    // Generate file download
    res.download('/path-to-file.txt');

    // redirect to other url
    res.redirect('/foo/bar');
    res.redirect('http://example.com');

    // Other response types
    res.send(new Buffer('whoop'));
    res.send({ some: 'json' });
    res.send('<p>some html</p>');
    res.status(404).send('Sorry, we cannot find that!');
    res.status(500).send({ error: 'something blew up' });
});

HTTPS with Express

Sometimes you'll need to access special features of the browser that are only available with secure connections, therefore you'll need to provide SSL support to your server.

To achieve it using Express you'll need to access the https module of node.js (available by default), then create a server using the createServer method and provide the path of the .pem certificates (if you want to know how to create).

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('certificates/key.pem', 'utf8');
var certificate = fs.readFileSync('certificates/cert.pem', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

// For http
httpServer.listen(8080);
// For https
httpsServer.listen(8443);

app.get('/', function (req, res) {
    res.header('Content-type', 'text/html');
    return res.end('<h1>Hello, Secure World!</h1>');
});

In this way you'll access localhost in secure mode using Express navigating to https://localhost:8443. If you want to know how to create the .pem required files to make your server works, please read this article.

Have fun !

Become a more social person