Creating a Web server with Node JS is fairly simple with Node JS which serves HTML view pages. For this purpose I am going to use Visual Studio to create Node JS Web Application type project.
If you are not able to find the template project for Node JS then most likely the packages for Node JS development are not installed from Visual Studio Installer.
Installing Node JS Development Tools
From the Visual Studio Installer select the Node js development tools and install them to create a Node js project as shown in the figure below.
Once its installed we can go ahead and create a empty Node JS web application.Required npm packages for this application would be
Server Application is the express App and since its a web application we need to use the http package to host the Application.
ejs-locals is a package stands for Embedded javascript Template pack using which we will be able to create html views using javascript.
Install the required packages using the npm package manager from the visual studio itself or using the command prompt.
Demo
Once the dependencies are installed you will see that these are added in the package.json file present in the Node JS application as shown below:
Next we have to add our server logic to our Web Application Startup file Server.js as shown below:
As shown in the server code above we are using the view engine as ejs. The default route path as specified by "/" returns a json with a label title from the relative path ejs/index. For this to work we have to create a index.ejs file in the path which uses ejs to embed the javascript code in the html. The folder structure is as shown in the figure below:
The content of the ejs file is shown below, which is a basic html template with placeholder for the title
In the server code when we assign the value for the title property, the view is generated with the correct value and is returned to the client as shown below:
Here the response is a html which is generated by the ejs view engine.
The other variant is to directly send the JSON data without view as shown in the case where the route path is "/app/user".
Comments
Post a Comment