Setting up a Simple Express.js Server: A Beginner's Guide

Setting up a Simple Express.js Server: A Beginner's Guide

Express.js is a popular JavaScript library for building web applications and APIs. It is built on top of Node.js and allows you to easily create servers and routes for handling HTTP requests.

To get started with Express.js, you will need to have Node.js and npm (Node Package Manager) installed on your computer. You can download and install Node.js from the official website (nodejs.org) or use a package manager like Homebrew (on macOS) or Chocolatey (on Windows).

Once you have Node.js and npm installed, you can create a new Node.js project by running the following command in a terminal:

mkdir my-project
cd my-project
npm init -y

This will create a new directory called "my-project" and initialize it as a Node.js project with a package.json file.

Next, you can install Express.js by running the following command:

npm install express

This will install the Express.js library and add it to your project's dependencies in the package.json file.

With Express.js installed, you can create an HTTP server by creating a file called "server.js" and adding the following code:

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

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

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
j

This code creates an Express.js app and sets up a route for the root path (/) that sends a "Hello World!" message to the client. It also sets up the server to listen on a port specified by the PORT environment variable, or 3000 if the variable is not set.

To start the server, you can run the following command in the terminal:

node server.js

This will start the server and you should see the message "Server listening on port 3000" in the terminal. You can then visit localhost:3000 in your web browser to see the "Hello World!" message.

You can add additional routes to the server by using the app.get(), app.post(), app.put(), and app.delete() methods. For example:

app.get('/hello/:name', (req, res) => {
  res.send(`Hello ${req.params.name}!`);
});
j

This route will match requests to the path /hello/ followed by a name and send a personalized greeting to the client.

You can learn more about creating servers and routes with Express.js by reading the official documentation (expressjs.com).

Did you find this article valuable?

Support Edwin Valerio by becoming a sponsor. Any amount is appreciated!