Simple REST server with NodeJS & express

  1. Installation
  2. The Code
  3. Further Reading

Installation

Install nodejs and npm (NodePacketManager) via sudo yum install nodejs npm
NodeJS is basically "Javascript" for servers. You can start the commandline-version by simply typing node.
Express is a minimalistic web framework for NodeJS. Install it via sudo npm install express.
Further Documentation of 'express' can be found at npmjs.com/package/express.
Now, for example, you can create a file named "simple.js" and paste the following example-code inside:


const express = require("express")
const app = express()
app.get("/", function(req, res){
  res.send("Hello World!")
})
app.listen(3000)

Now use the console command node simple.js to start the script. If you know visit localhost:3000 on your browser you will be greeted with a "Hello World!" page.
To stop the script simply press CTRL+C.

The Code

We can now add to the example from above.
We'll make a new 'route' (link) for our app which takes an ID and returns data from that.


const express = require("express")
const app = express()
var rdata = ["Apple","Strawberry","Cherry","Banana"]
app.get("/", function(req, res){
  res.send("Hello World!")
})
app.get("/:id", function(req, res){
  if(req.params.id < rdata.length){
    res.send("Data: "+_data[req.params.id]);
  }else{
    res.send("ID "+req.params.id+" can't be found.");
  }
})
app.listen(3000)

If you now start the server again you can access the rdata list by going to, for example, localhost:3000/1, which should print out the ID 1 and Data 'Strawberry'.
This also works, for example, for the route "/:category/:id", where you can access the parameters with req.params.category and req.params.id respectively.
This isn't the most secure or most fleshed out example, but it should give you an idea how you can build your own server.
A first good step would be to transfer the data to a database or JSON file and fetch it from there. To read a JSON file from the same folder you can simply use the following code snippet:

const fs = require("fs");
var rdata = JSON.parse(fs.readFileSync("data.json","utf8"));

This reads the data.json file into the rdata variable as an object, but be careful, because it uses the synchronized readFile version.

Further Reading

The example above is very simple and minimalistic.
The first thing you should look into next would be the MVC (Model View Controller) architecture that you should write for express. This splits the get-data, URL-Route, and send-data part into different files, because in our above example they are all in one file.

Another good idea would be to look into modules that easily connect your database to the NodeJS REST server. Getting data from JSON files isn't the best idea for a big amount of ever-changing data.