📜  express-js - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:41.428000             🧑  作者: Mango

Express.js - JavaScript

Express.js is a lightweight and fast web application framework for Node.js. It provides a simple and flexible API for building web applications and APIs. With Express.js, you can easily handle HTTP requests, manage sessions, handle middleware, and much more.

Installation

You can install Express.js using npm, the Node.js package manager.

npm install express
Hello World with Express.js

Here is how you can create a basic "Hello World" web application with Express.js:

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

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

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Notice that we use the app.get() method to handle an HTTP GET request on the root URL ('/'). When the request is received, we send the response with the string "Hello, World!".

Routing with Express.js

Express.js provides a powerful routing system that allows you to handle different HTTP requests for different paths. Here is an example:

app.get('/users', (req, res) => {
  res.send('List of users');
});

app.get('/users/:id', (req, res) => {
  const id = req.params.id;
  res.send(`User with ID ${id}`);
});

In this example, we define two routes: one for the path '/users', and one for the path '/users/:id'. The second route uses a URL parameter (:id) to capture the ID of a specific user.

Middleware with Express.js

Express.js allows you to define middleware functions that can handle requests and modify the response before passing it on to the next middleware or route handler. Here is an example:

const logger = (req, res, next) => {
  console.log(`[${new Date()}] ${req.method} ${req.url}`);
  next();
};

app.use(logger);

In this example, we define a middleware function called logger. The function takes three arguments: the request object (req), the response object (res), and the next function. The next function is used to pass control to the next middleware or route handler. Here, we simply log the date, HTTP method, and URL of the request.

Conclusion

Express.js is a powerful and flexible web application framework for Node.js. With its simple API, powerful routing system, and middleware architecture, it makes it easy to build fast and scalable web applications and APIs.