Yes, we know that node.js provides us with the JavaScript runtime to execute server-side code. That's good! That means we can design and implement some good console apps which can leverage the node.js runtime. But is it all that we want this great JavaScript runtime environment to offer? Of course not!
Yes, it's always better to give a bit of facelift to any existing entity. In the context of this blog, let us try to give this plain and simple server side code a chance to run within the confines of a web application rather than just playing around with the console.
Let's get started. First things first; for any developer working his way around to build a web application, he needs to simulate a web server type environment on his machine to make sure that the code he writes is actually building the right thing. To be able to test the functionality as well as to get a first hand taste of the UI components that would ultimately form and enhance the beauty of his web application.
With web applications leveraging node.js, things are no different. But yes, things do get a little bit easier for us developers whenever there is some piece of art readily available to save our time and effort. And the Express framework does exactly that.
Express is a node.js web application framework providing a robust set of features for building single, multipage and hybrid web applications. To put it simply, it offers just about the right infrastructure to make that code of ours execute inside the comforts of a web server. Without much ado, let's get down to how to set up Express in your potential web based node.js application.
npm install express --save
Type in the above command in the command line with the current directory being set to the application root.
This shall install Express framework to your application and register it to the set of dependencies defined in the
package.json file.
Next, we shall create a file that will handle all the Express related functionalities in the application. Let's name this file as server.js,
Next, we shall create a file that will handle all the Express related functionalities in the application. Let's name this file as server.js,
- --server.js code
- const express = require("express");
- var app = express();
- app.get("/", (req, res) => {
- res.send("Hello World");
- });
- app.get("/books", (req, res) => {
- res.send({
- message: "Hello Books"
- });
- })
- app.listen(3000, () => {
- console.log("The web server is up and running!");
- });
Let's take a deep look on the code presented above,
This code simply adds a reference to the Express framework and stores in a constant called "express" .
This fires up an instance of the Express server.
- const express = require("express");
- var app = express();
- app.get("/",(req,res)=>{
- res.send("Hello World");
- });




Kaushal PareekPosted Jul 30, 2018, 10:37 PM
Short and simple. Thanks for sharing