How to setup a simple server with Node.js Part I

Rosen Toshev
4 min readOct 8, 2019

--

Node.js is an open-source run-time environment that allows JavaScript to be executed on the server-side. Since its initial release in May, 2009 by Ryan Dahl, Node.js has grown vastly in popularity. In fact, ColorLib lists Node.JS as one of the best languages to learn in 2019. One of the reasons is that the server-side framework “uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest system of open source libraries in the world”.

Furthermore, Node.js has been used in the tech stacks for some of the most renowned companies. These companies include: Netflix, LinkedIn, Uber, PayPal, and the very own publishing platform you are currently reading this blog on, Medium. In addition to the above stated benefits of Node.js, one of the main reasons is that the same JavaScript developers that develop progressive web application’s (PWA) front-end can contribute their JS skills on the server-side, which provides a cost-effective solution for companies.

Setting up a basic server with Node.js

In order to set up a very basic Node.js server, we would first need to create a folder called `node-js-basic` with two files `run-server.js` and `server.js`

mkdir node-js-basic

Then, inside the directory create a new file called run-server.js. This is where we would be setting up the listener that listens on port 3000 of the localhost.

run-server.js

const server = require(‘./server’);
server.listen(3000, () => {
console.log(‘Server is up and listening on http://localhost:3000.');
});

Then we create aserver.js file. Here we use a router to match the url requests to the correct pieces of code, which is instrumental for setting up our basic get and post requests.

server.js

"use strict"const http = require('http')const finalhandler = require('finalhandler')const Router = require('router')const bodyParser = require('body-parser')const urlParser = require('url')const router = new Router({mergeParams: true})
let messages = []router.use(bodyParser.json())
router.get('/', (req, res) => {// Send a response to the client with the string 'Hello Node World!'res.setHeader('Content-Type', 'text/plain; charset=utf-8')res.end('Hello Node World!')})router.post('/message', (req, res) => {// Save the message and send the message id back to the clientlet newMessage;res.setHeader('Content-Type', 'application/json; charset=utf-8');newMessage = new Message(req.body.message);messages.push(newMessage);res.end(JSON.stringify(newMessage.id));
})const server = http.createServer((req, res) => {router(req, res, finalhandler(req, res))})exports.listen = function(port, callback) {server.listen(port, callback)}exports.close = function (callback) {server.close(callback)}};

A very important thing to note is that both the get and the post methods contain req (shorthand for request) and res (shorthand for response) as their parameters. The request object contains information and methods related to the "request" that has come in from the client. The responseobject contains information and methods about the server's response.

GET Method

The server awaits for a GET request to be send to the index path When the url request is made, the get method provides thecallback function that we supplied. The server is started with the following command:

node run-server.js

You can test the GET method either by:

  1. The GET method can be tested with the curl command
curl -X GET http://localhost:3000

2. The GET method can also be testing by sending a GET request with Postman to http://localhost:3000

Postman GET request

The server should now return the message “Hello Node World!”.

POST Method

Similar to the GET method, for the POST method as well we need to define a route and then write a callback function that defines the steps the server should follow to produce the desired response. We use the POST method to store our message in memory. After the imports, which are defined in the beginning of the file, we define an array where we store the messages let messages = []; The POST method is used to send messages to the server.

router.post('/message', (req, res) => {// Save the message and send the message id back to the clientlet newMessage;res.setHeader('Content-Type', 'application/json; charset=utf-8');newMessage = new Message(req.body.message);messages.push(newMessage);res.end(JSON.stringify(newMessage.id));})

If the server is not running, we need to run the server again:

node run-test.js

You can POST your message either by:

  1. The Curl method is used to post messages to the server. The req.body.message defines the request object that is passed to our callback function as an argument. For this, we use the body parser middleware to parse data that the server receives in the request body.
curl -X POST -H "content-type: application/json" http://localhost:3000/message -d '{"id":1,"message":"Our first message."}'

2. A POST request can be sent to http://localhost:3000/message. This POST request needs to be sending the message object {“id”:1, “message": “Our first message.”}in its body.

Postman POST method

The server should now return the id of the message, which in this case is 1.

--

--

Rosen Toshev
Rosen Toshev

No responses yet