Implementing URL Paths in NodeJs

Jordan Stubblefield
3 min readMar 1, 2017

In order to implement a URL path in NodeJs, we simply have to route requests and send responses back from the server based on the url sent in the request. There is no physical path or directory we are referring to, just a virtual path coded into the server. So how do we implement that?

First, start out with a basic server.

// server.jsvar http = require('http');var server = http.createServer(function(request, response) {

}.listen(3000, '127.0.0.1');

So now that we have a basic server, before we send our request over to the request handler, let’s set up a router to ensure that requests to specific URLs are handled properly. Note that we must instantiate ‘http’ variable that imports NodeJs’ native method and enable us to use that method.

// server.jsvar http = require('http');
var url = require('url');
var handleRequest = require('./request-handler.js');
var utilities = require('./utilities.js');
var routes = {
'/message-app/messages': handleRequest
};
var server = http.createServer(function(request, response) {
var urlParts = url.parse(request.url);
var route = routes[parts.pathname];
if (route) route(request, response);
else utilities.sendResponse(response, 'Not Found', 404);
}).listen(3000, '127.0.0.1');

Let’s explain the above code real quick. It’s a complete file for the sake of this example. We will get to the request-handler in just a sec. The routes object houses the different paths on this server that a client can access and request data. Inside the server, the urlParts variable utilizes the ‘url’ method, which has a parse method available to it. This will split the passed in URL into parts, including the protocol, domain, path, parameters, etc. We are concerned about the pathname only. In our example above, if it isn’t one of the paths we are expecting (‘/message-app/messages’) then we return a 404 error, but if it is we pass it off to the handleRequest function, imported from request-handler.js. I’m only going to cover ‘GET’ requests in this example.

// request-handler.jsvar utilities = require('./utilities.js');var actions = {
'GET': function(request, response) {
utilities.sendResponse(response, {results: messages});
};
module.exports = function(request, response) {
var action = actions[request.method];
if (action) action(request, response);
else utilities.sendResponse(response, 'Not Found', 404);
};

// utilities.js
var headers = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers': 'content-type, accept',
'access-control-max-age': 10,
'Content-Type': 'application/json'
};
exports.sendResponse = function(response, data, statusCode) {
statusCode = statusCode || 200;
response.writeHead(statusCode, headers);
response.end(JSON.stringify(data));
};

I separated the sendResponse function into its own file because I use it in the other two files. So just include the require line in both files to use the function. Once server.js has determined that request.url is existent on the server, it will pass the request to the request handler, which will determine the proper handling of the request. In our example, if the request.method is a ‘GET’ request, it will trigger the sendResponse function in utilities.js and pass in the response and results array. I did not pass in a statusCode because the default code is 200, which is what I want with a ‘GET’ request. The sendResponse function will create a header with the statusCode and headers and then it will end the response with the stringified version of the results and send it back to the client. Paths complete!

--

--