Skip to content

Setting Up Express.js

Installing Express.js in a Node.js Application

To get started with Express.js, you first need to install it in your Node.js project. You can do this by running the following command in your project directory:

Terminal window
npm install express

Once installed, you can use require to include Express in your Node.js application.

Creating a Basic HTTP Server with Express

Once you’ve installed Express, you can create a simple HTTP server with just a few lines of code. Here’s an example:

const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello, world!");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
  • express() initializes an Express application. This is the main entry point for creating an Express server.

  • app.get() defines a route that listens for GET requests on the root path (/). When a request is made to this path, the server responds with the string 'Hello, world!'.

  • app.listen() starts the server and makes it listen for incoming requests on a specified port (in this case, 3000). Once the server is up and running, it logs a message to the console indicating the server’s status and the URL where it can be accessed.