Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Defining the Entry Point of the API | Building REST APIs with Node.js and Express.js
Backend Development with Node.js and Express.js

book
Defining the Entry Point of the API

The index.js file is where we configure our server, define middleware, set up routes, and handle errors. It serves as the heart of our Express application.

Import required modules and files

index.js is where we configure our server, define middleware, set up routes, and handle errors. Let's break down the code step by step.

js
const express = require("express"); // Import the `Express` framework
const app = express(); // Create an `Express` application instance
const router = require("./routes/postsRoutes"); // Import the `router` module for posts
const PORT = process.env.PORT || 3000; // Define the port for the server

Middleware for JSON Parsing

js
app.use(express.json()); // Use the `express.json()` middleware for parsing JSON requests

The express.json() middleware parses incoming JSON requests and makes the data available in req.body. It's crucial for handling JSON data in our POST and PUT requests.

Route Setup

Routing defines how our application responds to client requests.

js
app.use("/api", router); // Use the router for handling routes under the `"/api"` path

Routing defines how our application responds to client requests. In this line of code, we specify that the router defined in postsRoutes.js should handle routes under the /api path.

Error Handling Middleware

Error handling is crucial to ensure our application handles errors gracefully.

js
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error to the console
res.status(500).json({ error: "Internal Server Error" }); // Send a 500 Internal Server Error response
});
  • This middleware is responsible for catching errors that occur during request processing. If any middleware or route handler before it calls next(err), this middleware will catch the error;
  • It logs the error to the console using console.error(err.stack);
  • It sends a 500 Internal Server Error response to the client, indicating that something went wrong on the server.

Starting the Server

To complete our application setup, we start the Express server on a specified port.

js
// Start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`); // Log a message indicating the server is running
});
  • This line starts the Express server and makes it listen on the specified port (PORT);
  • When the server starts, it logs a message to the console indicating the port on which it's running.

Complete code of the index.js file

js
// Import required modules and files
const express = require("express"); // Import the `Express` framework
const app = express(); // Create an `Express` application instance
const router = require("./routes/postsRoutes"); // Import the `router` module for posts
const PORT = process.env.PORT || 3000; // Define the port for the server

app.use(express.json()); // Use the `express.json()` middleware for parsing JSON requests

app.use("/api", router); // Use the `router` for handling routes under the `"/api"` path

// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error to the console
res.status(500).json({ error: "Internal Server Error" }); // Send a `500 Internal Server Error` response
});

// Start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`); // Log a message indicating the server is running
});

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
some-alt