Building a Simple Express.js Application

Profile Picture

princepalkanpur007

Sunday, 2024-07-21



Express.js is a popular web application framework for Node.js that makes building robust and scalable server-side applications a breeze. In this tutorial, we’ll walk through the steps of creating a basic Express.js application from scratch. By the end, you’ll have a foundational understanding of how to set up and run an Express.js app.


1. Prerequisites


Before we begin, make sure you have the following installed:


2. Setting Up Your Project


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


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


Initialize a new Node.js project by running:


npm init -y


This command creates a package.json file with default settings.


3. Installing Express


Next, install Express.js using npm:


npm install express


This command adds Express to your project dependencies.


4. Creating the Application


Create a new file named app.js (or index.js) in your project directory:


touch app.js


Open app.js in your code editor and add the following code:


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

// Middleware to parse JSON bodies
app.use(express.json());

// Define a simple route
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

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


5. Understanding the Code


  • const express = require('express'); – Imports the Express module.
  • const app = express(); – Creates an Express application.
  • app.use(express.json()); – Adds middleware to parse JSON request bodies.
  • app.get('/', (req, res) => { ... }); – Defines a route that responds with “Hello, world!” when accessed via GET request.
  • app.listen(port, () => { ... }); – Starts the server on the specified port and logs a message to the console.


6. Running Your Application


To start your Express.js application, run the following command:


node app.js


You should see the message "Server is running at http://localhost:3000" in your terminal.

Open your browser and navigate to http://localhost:3000. You should see the “Hello, world!” message.


7. Adding More Routes


You can define additional routes to handle different endpoints. For example, add the following routes to app.js:


// Route to handle GET requests to /about
app.get('/about', (req, res) => {
  res.send('This is the About page.');
});

// Route to handle POST requests to /data
app.post('/data', (req, res) => {
  const data = req.body;
  res.json({ receivedData: data });
});


8. Error Handling


To handle errors, you can add a middleware function at the end of your route definitions:


app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});


9. Conclusion


Congratulations! You’ve created a simple Express.js application. From here, you can explore more advanced features of Express.js, such as routing, middleware, and integration with databases. Express.js is a powerful framework that simplifies server-side development and helps you build scalable applications quickly.

Feel free to experiment with different routes and middleware to enhance your app. Happy coding!

How did you feel about this post?

😍 🙂 😐 😕 😡