Table of Contents
Why Node.js?
Node.js allows the user to write backend code in JavaScript instead of PHP, Python, Java or any other language.
To be a full-stack developer, you had to be fairly fluent in more than one programming language, but with Node.js, our entire web application can be written in JavaScript.
Express:
There are many different npm packages that can be used to write Node.js servers, we’re going to use Express, because
- Express is fast and un-opinionated web framework.
- It’s very easy to get started with, and very well documented.
- There are a ton of third party add-ons that can be used to extend its functionality.
Setting up an Express server.
Setting up your express server is pretty straight forward. You need to have NodeJS on your local machine. Install the latest version of node from NodeJs.
- Create a new directory called backend in your project directory.
- Open up your terminal and navigate to your backend directory
- To initialize this folder as an npm package run the following command
PS C:\Users\Lenovo\Desktop\My-Blog\backend> npm init -y
- This will create a “package.json” file in your backend folder.
- Now, install Express by:
PS C:\Users\Lenovo\Desktop\My-Blog\backend> npm install --save express
- Create a new src folder in your backend directory.
- Inside the src folder, create a js file called server.js
This server.js file is where we will write our backend code.
Currently NodeJS does not support JavaScript’s modern ES6 syntax. To use ES6 we need to install a few packages from babel.
(For those of you who are not familiar with babel, it is a transpiler that allows us to write our codebase in ES6 syntax, where ES6 is not supported natively for e.g NodeJS)
Install the required babel packages by this command:
PS C:\Users\Lenovo\Desktop\My-Blog\backend> npm install --save-dev @babel/core @babel/node @babel/preset-env
- Create a new file in your src directory called .babelrc.
This file is where we tell babel how we want to transform the ES6 code that we write, into common javascript code that NodeJS can execute. This is really simple as shown in the picture below.
Write your first Server Side code.
We are going to start with a simple express server that just sends us a message when we send request to it.
Open up your server.js file and write the following code.
import express from "express"; const app = express(); app.get("/hello", (req, res) => res.send('Hello!')); app.listen(8000, () => console.log("Listen on port 8000"));
- First two lines are including and initializing express. Third line is making a ‘GET’ request to the server, whose first parameter is an endpoint (i.e. route) and second is the callback with a request and a response object.
- In this example, we are just sending (“Hello!”) as a response, inside our body. Last line just starts our server by the function listen, which takes first argument as a port which it is listening on, and the second is just a call back that is displayed on our terminal
- Open your terminal and type the following command to run the server.
PS C:\Users\Lenovo\Desktop\My-Blog\backend> npx babel-node src/server.js
Now, Open up your browser and type localhost:8000/hello and you can see the message displayed
Testing an Express server with Postman.
So far, we are testing our backend by typing URL into our browser, but this method is not good enough for complicated operations that we want to implement. For this purpose, we’re going to use a tool called postman. It is very common free piece of software used by many developers for testing purposes to build a backend.
Download and install postman from here.
- Start your backend server from the terminal and open postman.
- Select the type of request (in this case ‘GET’)
- Enter the URL localhost:8000/hello and click send. You can see the message being displayed in response tab as shown below.
Post Request: We will take the above example and we will pass in the URL with some JSON data in postman body with type POST as shown in the picture below.
- Go under the body tab, select raw from the dropdown menu.
Now, instead of Text, select JSON (application/json) and type in your name.
Now open your backend terminal, and to include this data in our backend code, we need to install a package called body-parser by
PS C:\Users\Lenovo\Desktop\My-Blog\backend> npm install --save body-parser
- Open server.js
- Import body parser from the package and include the json file by “use” function (as shown below)
import express from "express"; import bodyParser from "body-parser"; const app = express(); app.use(bodyParser.json()); app.post("/hello", (req, res) => res.send(`Hello ${req.body.name}`)); app.listen(8000, () => console.log("Listen on port 8000"));
(In the body, we are sending a response using backtick instead of inverted comma, which is an ES6 syntax, to include the name data in the json file as shown in the picture above)
Route parameters in Express.
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Let’s take an example
- Open your server.js file.
- Write a ‘GET’ request, this time we will write the route as “/hello/:name”.
- Inside the callback function, we are going to send a response (`Hello ${req.params.name}`) as shown below
Note that instead of req.body we are using req.params
import express from "express"; import bodyParser from "body-parser"; const app = express(); app.use(bodyParser.json()); app.get("/hello/:name", (req, res) => res.send(`Hello ${req.params.name}`)); app.listen(8000, () => console.log("Listen on port 8000"));