How to use Express JS with Node JS


Installing Express.js

Express.js is a Node.js framework used for building web applications and APIs. To get started with Express.js, you need to install it in your Node.js project. Here's a step-by-step guide to installing and setting up Express.js.


Prerequisites

  1. Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed. You can check if they're installed by running:

    node -v npm -v

    If they are not installed, you can download and install them from the Node.js website.


Steps to Install Express.js

1. Create a New Node.js Project

First, create a new directory for your project and navigate into it:

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

2. Initialize a New npm Project

Initialize a new npm project by running:

npm init

This command will prompt you to enter information about your project, such as the project name, version, description, entry point, and more. You can also use npm init -y to generate a default package.json file with default values.

3. Install Express.js

Install Express.js using npm:

npm install express

This command will add Express.js to your node_modules directory and update your package.json file to include Express.js as a dependency.

4. Create Your First Express.js Application

Create a file named app.js (or index.js, server.js, etc.) in your project directory. Open this file in your text editor and add the following code to set up a basic Express.js application:

const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

This code does the following:

  • Imports the Express.js module.
  • Creates an Express application instance.
  • Defines a route for the root URL (/) that responds with "Hello World!".
  • Starts the server on port 3000 and logs a message to the console.

5. Run Your Express.js Application

Start your Express.js application by running:

node app.js

You should see the message:

Server running at http://localhost:3000

Open your web browser and navigate to http://localhost:3000. You should see "Hello World!" displayed on the page.


Summary

  1. Create Project: Set up a new directory for your project.
  2. Initialize npm: Run npm init to create a package.json file.
  3. Install Express.js: Use npm install express to add Express to your project.
  4. Create Application: Write a basic Express.js application in a file (e.g., app.js).
  5. Run Application: Use node app.js to start the server and test your setup.

Express.js is now installed and your basic application is running. You can start building more complex routes and adding middleware as needed for your project.