InterviewSolution
| 1. |
How to create an HTTP server using Express? |
|
Answer» To create an HTTP SERVER with Express.js, we need to serve HTML pages. We can serve the HTML code with templating engines like EJS also, but here we will DIRECTLY serve the HTML, CSS, and JavaScript files. First, we will have our Node runtime installed and CREATED using npm init -y. We will also install express in our Node.js app. After that, we will create a public folder and an index.html file in it and put the simple content in it. Next, we will create a style.css file in the public folder. Here we are giving the styles for a beautiful gradient background.. Now, create a main.js file in the public folder. Here, we had put the code for a simple alert. Then, we will create the server.js file and import the path and express. After that we are using app.use and inside it using path, which is required to generate static paths and serve static ASSETS. And lastly, we are serving the index.html file through the sendFile. Now, start the server by giving the node server.js in the terminal. When we go to http://localhost:8080/ and we will see this beautiful webpage with the alert. |
|