Express JS

Here’s a step-by-step guide to learning Express.js with code examples:

  1. Installation: To get started with Express, you first need to install it. You can do this using npm, the package manager for Node.js:
npm install express
  1. Basic Setup: Once you have installed Express, you can create a new Express application by creating a new JavaScript file and requiring the Express module:
const express = require('express');
const app = express();
  1. Routes: In Express, routes are used to handle HTTP requests. You can define a route using the app.get() method, which takes two arguments: the route path and a callback function that handles the request and response objects:
app.get('/', (req, res) => {
  res.send('Hello, World!');
});
  1. Middleware: Middleware functions are functions that can be used to modify the request or response objects, or to perform additional tasks before the route handler function is called. You can add middleware functions using the app.use() method:
app.use((req, res, next) => {
  console.log('Request received at', new Date());
  next();
});

In this example, the middleware function logs the current date and time whenever a request is received, and then calls the next() function to continue processing the request.

  1. Serving Static Files: Express also provides a built-in middleware function for serving static files (such as CSS or JavaScript files). You can use the express.static() function to specify the directory where your static files are located:
app.use(express.static('public'));

In this example, the public directory is specified as the location for the static files.

  1. Error Handling: You can handle errors in Express using middleware functions that have four arguments (the first argument is an error object). You can use the app.use() method to define an error-handling middleware function:
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send('Server Error');
});

In this example, the error-handling middleware function logs the error to the console and sends a 500 status code with the message “Server Error”.

  1. Running the Server: Finally, you can start the Express server by calling the app.listen() method and specifying the port number:
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In this example, the server is started on port 3000, and a message is logged to the console once the server is running.

Basic Hello world:

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

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Leave a Comment

Skip to content