1735221096

Building web application with Express.js


Express.js([https://expressjs.com](https://expressjs.com)), or Express, has been and remains the most popular web framework for building web application in Node.js. In this post, we will look at how to create an Expressjs web server. ## <br>Getting ready --- To get started, we'll create a folder named **express-app** and initialize our project by running the following commands: $ mkdir express-app $ cd express-app $ npm init --yes ## <br>How to do it --- In this recipe, we'll create a web server that responds on the / route using. 1. First, let's start by installing the `express` module: $ **npm install express** 2. Now, we need to create a few directories and files for our web application. While in your `express-app` directory, enter the following commands int your Terminal: $ touch app.js $ mkdir routes public $ touch routes/index.js public/style.css 3. Our app.jss file is where we instantiate `express`. Open the `app.js` file and import the following dependencies: ```js const express = require("express"); const path = require("path"); const index = require("./routes/index"); ``` 4. Next we'll define the port for our express.js server: ```js const PORT = process.env.PORT || 3000; ``` 5. Now we can initialize `express`: ```js const app = express();; ``` 6. Next we'll register the `static` Express.js middleware to host the public directory. We will also mount our `index` route: ```js app.use(express.static(path.join(__dirname, "public"))); app.use("/", index); ``` 7. Finally, in `app.js`, we need to start our Express server on our specified port: ```js app.listen(PORT, () =>{ console.log(`Server listening on port ${PORT}`); }); ``` 8. We now need to add our route handling in the `index.js` file that is within the `routes` directory. Add the folllowing to `index.js`: ```js const express = require("express"); const router = express.Router(); router.get("/", (req, res) => { const title = "Express"; res.send(` <html> <head> <title>${title}</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>${title}</h1> <p>welcome to ${title}</p> </body></html> `); }); modul.exports = router; ``` 9. Now we can add some styling to our application using CSS. Add the following to `public/styles.css` ```css body { padding: 50px; font: 14px "Lucida Grande", Helvetica Arial, sans-serif; } ``` 10. Now we can start out Express.js server by running the following command: ```bash node app.js ``` Navigate to [https://localhost:3000](https://localhost:3000) and you will see the result in your browser. If you like content like this, take part in the site by commenting or liking it. Thank you

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2025 © Chat-to.dev]