leonero leonero - 5 months ago 9
Node.js Question

Add new path to nodejs server

I've created the following nodejs server:

var http = require('http');

var serverFunction = function(req, res) {
if (req.url === '/') {
//does something
}
}

http.createServer(serverFunction).listen(3000);


And now I want to add another path (example: /hello), but I don't want to change serverFunction.

How can I do that?

Answer

The higher level way of creating multiple independent request handlers is to use a simple framework like Express. While one is not technically needed to do what you're asking, Express is built to make tasks like that easy.

A simple express server with multiple route handlers would look like this:

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

app.get('/', function(req, res) {
    // handle the / route here
});

app.get('/hello', function(req, res) {
    // handle the /hello route here
});

app.listen(3000);

The Express framework is built to allow you to add routes as simply as shown above. It also includes many, many more features such as middleware processing and access to lots of pre-built middleware modules such as cookie handling, session handling, post handling, etc...


In strict answer to your original question (though I don't think this is the easiest way to add more route handlers), if you want to use the plain http module and not add the second route to your existing listener, you could listen for the request event on the server.

var http = require('http');

var serverFunction = function(req, res) {
    if (req.url === '/') {
        //does something
    }
}

var server = http.createServer(serverFunction).listen(3000);

server.on('request', function(req, res) {
    // see all incoming requests here
    if (req.url === '/hello') {
        // process /hello route here
    }
});

In fact, if you read the http server doc carefully, you will see that your serverFunction is nothing more than an automatically registered listener for the request event and as with event-style interfaces, you can just create more listeners for that event if you choose.