Run your web server backend with JavaScript

Using NodeJS and ExpressJS JavaScript NodeJS





Setup

This guide will teach you how to run a webserver via NodeJS with JavaScript using a module called ExpressJS. This way your entire backend will be in JavaScript. Node can easily be run by any server.

First we will need to install NodeJS and NPM. This is specific to every platform so I suggest you look up how to install it if you run into problems there. On Linux you usually use your package manager and on Windows you download the installer from their website.

Once we have it installed, we can start. Make a new folder and navigate into it. Run the command

npm init

It will ask you questions about the name of the project, description and so on. You only really need a name, the rest is optional / will default when you skip.
After that you can start installing modules and defining the scripts.
Alongside the “test” script, the “start” script exists by default. This one you will have to change in order to run your project.
Create an empty javascript file with whatever name you choose.
Then, the simplest way to run your project is simply:

node yourfile.js
Put that command in the package.json in the start script. Then you run your project by just using

npm start

Now we need to install the modules we need. In this case expressJS and body parser which will help us later to handle POST requests.
Run:

npm install expressjs --save
npm install body-parser --save

The --save will make it add it to your package.json.

Now we have everything and we can start with the code.




Imports

The most import module to import of course is expressJS, which is the library that handles all the server related activity:

const express = require('express');

Some other imports you may consider are:

const http = require('http');
const https = require('https');
const path = require('path');
const fs = require('fs'); 
const bodyParser = require('body-parser');

HTTPS and HTTP in case you need to make those kind of external calls.
Path can help with forming paths to files, more of that later.
FS is filestream, to read and write files which is usually pretty important.
Body Parser is very important for POST calls and will be explained later.




Initializations

First we need to initialize ExpressJS itself, in order to access the functions given:

const app = express();

Now we want to add the following two lines:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

The first line enables JSON encoding/decoding, which happens frequently for POST communication calls inside the body. The second line is to decode arguments/fields inside a POST request, the exact MIME type that is decoded here is called: application/x-www-form-urlencoded.




Code

First, in order to start the server per se and listen to a specific port, use:

app.listen(3000, function () {
    console.log('Listening on port 3000.');
});
It’s pretty much as simple as that. Use any port you like. The body of the function is executed upon starting the server. Calling the listen function is mandatory to get the server to function.




Routes

Now we have to define which urls we want to respond to and via what method, meaning GET, POST and/or PUT.
There are different ways of doing this:
app.route() Example:

app.route('/something)
.get(function(req, res) {
   res.send(‘GET was called’)  );
})
.post(function(req, res) {
   res.send('POST was called’ );
})
.put(function(req, res) {
   res.send(‘PUT was called);
});
Using this syntax you can define a route and then chain these handlers.

Simple and direct example:
app.post('/api/users', function(req, res) {
    var user_id =;
    var token = req.body.token;
    var geo = req.body.geo;

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

app.get('/', function(req, res) {
	//GET on / aka just root
});

This would be the simple way, where we give the route directly there in the function call.
There is also app.all() which just responds to all types of requests on a specific route.

The route is a string; However you can also use wildcards in there, using an asterisk * , symbolizing any amount of random characters. You can also use a regular expression by starting out with a slash instead of quotation marks used for a string.

Using the response object you can send an entire file to the user. So if you want to serve a fixed html directly to the user, this is a very easy way. But it also offers no flexibility. You send the file as it is. If you want to change the file before sending, where the changes may depend upon the situation and the data, one way to do it is to use FileStream to load in the HTML file first, then manipulate it and then serve it as a string via res.send();
Example:

fs.readFile('filename', (err, data) => {
               //data.toString()
           });

Usually this is not done manually but it goes into the direct of using a framework like Angular.



To work with the arguments sent in a request, you need aforementioned setups that we did, for POST, to decode these. Afterwards this is how you access them:
For POST: req.body.variable
For GET: req.query.variable




Static Files

All css files or referred Javascript files, any images, all files that may be reached directly or via other files referring to them have to be mapped. This is done by using static folders similar to mounting folders on linux.

Basically you just make a folder and then map it, like:

app.use(express.static('public'));
Assuming there is a folder called “public” in the same folder as this javascript file. Then once you mapped that folder, everything in there is accessible. You will not need to name the folder “public”, that is automatically searched. Just subfolder names and file names.

If you have a lot of routes which are not just in one big static folder, it can make sense such it can make sense to define these in a config type json file, instead of in the code directly. The organizational usefulness also depends if those routes do a lot of different things.




Paths

In some circumstances, usually on Windows, slashes can be misinterpreted. But in general it should be fine using paths with slashes. The path module will create path strings appropriately.
path.join('somefolder', 'anotherfolder', 'file.ext');

All you need to do is run this node program on your webserver and you are ready to go.


Real World Example

Check out Currency Converter Website with NodeJS & Express JS for a real world example.

Comments

Loading…

We use cookies and other technologies to improve your experience on our website and to analyze our traffic. By browsing our website, you consent to our use of cookies and other tracking technologies.

Accept cookies and close this message
Win now