Simple Web Server And REST API Using NodeJS And Express
NodeJS, is a JavaScript run-time based on Google’s Chrome V8 JavaScript engine.
Introduction
To get started - Please make sure that your version of Node is at least v10.18.0 or later.
You can check your node version using: node -v
. Or if you haven’t installed it yet, install the NodeJS from here-
https://nodejs.org/en/
NodeJS vs JavaScript
JavaScript | NodeJS |
---|---|
“Referring only JavaScript” means code running on the client-side (i.e on the browser). | “Whereas NodeJS” is a unique implementation of JavaScript running on the server side. |
Includes: Client side activity like clicks, animation, popup, etc. and makes web page interactive | Includes: Server side activity like backend APIs, executing commands, accessing and performing non-blocking operations, system services etc. and provides service on level of operating system |
JavaScript: simply runs on browser engines, like Spider monkey (FireFox), JavaScript Core (Safari), V8 (Google Chrome) etc. | NodeJS: simply the V8 engine bundled with libraries to do I/O, networking, backend services and lot more on system server and harware |
JavaScript is synchronous and blocking | NodeJS is asynchronous and non-blocking |
To learn more on JavaScript See:
1. Getting Started
Lets create a new template for our application with the-
|
|
Initialize project name and enter the promoted details.
This will generated the package.json file at the root of the project.
|
|
We have initializer for our app. main: “index.js” , is the entry point of the application Edit the index.js with the following code:
|
|
We can run the program directly with Node from the command line:
|
|
or we can edit and the script, in our package.json to run as npm script.
|
|
Now the script “start” can be run using command npm start
.
3. Web Server using built in http module
Now, Lets Write code for starting web server. In your index.js:
|
|
Start the app npm start
or node index.js
to run.
We can now open our application in the browser http://localhost:3001. Note: You may get the error - “Error Address in use 3001. This may happen if you didnt stop the previous instance you started or some app is using the port.
|
|
Now Lets serve the Json file. Steps to follows:
|
|
We have sucessfuly created the app. However, serving the application with Node’s built-in http is cumbersome, especially once the application grows in size. Now comes the Express, the most popular library for running our web server.
4. Web server using Express library
Let’s install express in our application and quickly get started with it.
|
|
–save will also add it to our package.json file
|
|
Let’s get back to our application and make the following changes:
|
|
Start the app. npm start
.