seeb4coding nodejs

How to Set Up a Simple Node.js and Express App

When you’re starting out with Node.js, one of the best ways to quickly build a web server or web application is to use Express.js. This guide will take you through the step-by-step process of setting up a basic Node.js and Express.js app, including creating project folders, serving HTML, CSS, and JavaScript files, and testing the app in your browser.

Step 1: Set Up Your Development Environment

Before diving into the code, ensure that Node.js and npm (Node Package Manager) are installed on your system.

  • Download Node.js: Head over to the official Node.js website to download and install the latest version.
  • Verify Installation: Open a terminal and check if Node.js and npm are installed correctly by running the following commands:
node -v
npm -v

You should see the installed versions of Node.js and npm.


Step 2: Create a Project Folder

Create a new folder where your Express project will reside.

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

This creates a folder named my-express-app and navigates into it.


Step 3: Initialize a Node.js Project

Initialize a new Node.js project inside your folder. This will generate a package.json file to manage your project’s dependencies.

npm init -y

The -y flag automatically accepts the default settings without any prompts.


Step 4: Install Express

With Node.js initialized, the next step is to install Express.

npm install express

This command installs Express and adds it as a dependency in your package.json file.


Step 5: Create Your Express App

Next, you need to create the core of your app.

  • Create a file named app.js in your project folder.
  • Add the following code to app.js:
const express = require('express');
const app = express();
const port = 3000;

// Home route
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

This basic setup includes:

  • Express initialization.
  • A simple route that responds with “Hello, World!” when visiting the homepage (/).
  • The server listens on port 3000.

Step 6: Start Your Express App

To run the server:

Make sure you’re in the project folder:

cd my-express-app

Start the app using the following command:

node app.js

Your terminal should display Server is running on port 3000.


Step 7: Test Your Express App

Open a web browser and go to:

  • URL: http://localhost:3000

You should see the message “Hello, World!” displayed.


Folder Structure Overview

At this stage, your project folder should look like this:

my-express-app/
├── node_modules/       # All installed npm packages
├── package.json        # Project metadata and dependencies
├── package-lock.json   # Lockfile for npm
├── app.js              # Main application file


Step 8: Adding HTML, CSS, and JS Files

To serve static files such as HTML, CSS, and JavaScript, you need to configure Express to serve these files from a folder.

Create a Public Folder

Create a directory named public in your project folder.

mkdir public

Inside public, add the following files:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Express App</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Welcome to Express.js!</h1>
    <script src="app.js"></script>
</body>
</html>

style.css:

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
}

app.js (Frontend JavaScript):

console.log('Frontend JS is working!');

Serve Static Files in Express

In your app.js (main Express file), configure Express to serve static files from the public folder:

app.use(express.static('public'));

Then, modify the route to serve the index.html file:

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

Step 9: Redirects in Express

Express also allows you to easily redirect users. To implement a redirect, add a new route to your app.js:

app.get('/old-route', (req, res) => {
  res.redirect('/new-route');
});

app.get('/new-route', (req, res) => {
  res.send('You have been redirected!');
});

In this example, visiting /old-route will automatically redirect users to /new-route.


Conclusion

You now have a fully functional Node.js and Express application! You’ve learned how to:

  • Initialize a Node.js project.
  • Install Express.
  • Serve static HTML, CSS, and JavaScript files.
  • Set up routes and test them.
  • Implement simple redirects.

This guide provides a great foundation for building more advanced web applications with Express. You can continue adding new routes, static assets, and functionalities as you expand your project.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *