,

Setting up files and routing to pages with Node.js and Express.js – Class 1

Posted by

Node.js with Express.js: File Setup and Routing

Node.js with Express.js: File Setup and Routing

Node.js and Express.js are popular tools for building web applications. In this article, we will discuss the file setup for a Node.js with Express.js project and how to set up routing to different pages.

File Setup

First, let’s set up the basic file structure for our Node.js with Express.js project.

Create a new directory for your project and navigate into it using the command line.

mkdir my-express-app
cd my-express-app

Next, initialize a new Node.js project using npm.

npm init -y

This will create a package.json file with default values.

Next, install Express.js as a dependency for your project.

npm install express

Routing to Pages

Now that we have our file structure set up, let’s create a new file called app.js to define our Express.js application and set up routing to different pages.

touch app.js

Open the app.js file in your text editor and add the following code:


const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the homepage');
});

app.get('/about', (req, res) => {
  res.send('About Us');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, we have defined two routes using the app.get() method. The first route handles requests to the root URL and sends a welcome message. The second route handles requests to the /about URL and sends a message about the page.

Save the app.js file and return to the command line. Use the following command to start the Express.js server:

node app.js

Now, open your web browser and navigate to http://localhost:3000/ to see the welcome message. You can also visit http://localhost:3000/about to see the message about the page.

Conclusion

In this article, we have discussed the file setup for a Node.js with Express.js project and how to set up routing to different pages. With this knowledge, you can start building more complex web applications using Node.js and Express.js.