Getting Started with Express.js
Getting Started with Express.js
Before you can start building with Express.js, you’ll need to make sure your environment is properly set up and you understand the basic process of creating an Express server.
Prerequisites
To use Express, you must have Node.js installed on your system.
[!NOTE] If you haven’t installed Node.js yet, head over to the official Node.js website to download and install it.
1. Initializing Your Project
First, create a new directory for your project and navigate into it using your terminal:
mkdir my-express-appcd my-express-appNext, initialize a new Node.js project. This command creates a package.json file which will keep track of your project’s dependencies:
npm init -yThe -y flag automatically accepts all default options for the package.json file.
2. Installing Express
Now that your project is initialized, you can install Express.js via npm (Node Package Manager):
npm install expressThis will download Express and add it as a dependency in your package.json file.
3. Creating Your First Server
Create a new file named index.js (or app.js) in your project directory. This will be the main entry point for your application.
Add the following code to index.js to create a basic web server:
// 1. Import the express moduleimport express from 'express';
// 2. Create an instance of an Express applicationconst app = express();
// 3. Define the port numberconst PORT = 3000;
// 4. Define a basic routeapp.get('/', (req, res) => { res.send('Hello World! Welcome to Express.');});
// 5. Start the serverapp.listen(PORT, () => { console.log(`Server is running and listening on http://localhost:${PORT}`);});[!IMPORTANT] To use
importsyntax, make sure you add"type": "module"to yourpackage.jsonfile. Otherwise, you’ll need to useconst express = require('express');instead.
4. Running the Application
To start your newly created server, run the following command in your terminal:
node index.jsYou should see the message Server is running and listening on http://localhost:3000 logged in your console.
Open your web browser and navigate to http://localhost:3000. You will see “Hello World! Welcome to Express.” displayed on the page!