📅  最后修改于: 2023-12-03 14:42:05.329000             🧑  作者: Mango
import { Application } from "express"
When building a Node.js application, one of the most popular frameworks to use is Express.js
. This framework simplifies the creation of APIs tremendously and provides developers with a convenient way of handling requests, responses, and headers.
In order to use Express.js
, we need to import its core module. One of the main classes exported by the module is the Application
class. We import the Application
class by adding the following line to our code:
import { Application } from "express";
This line of code allows us to create instances of the Application
class and use its various methods and properties to handle HTTP requests.
To create an instance of the Application
class, we can simply call its constructor:
const app = new Application();
This creates a new Express.js
application with default settings. We can then configure the application by adding middleware, routes, and other features to it.
One of the most important features of Express.js
is middleware. Middleware is a function that is executed for every incoming request. This function can modify the request object, add new properties to it, or modify the response object. To add middleware to an Express.js
application, we use the use
method of the Application
class:
app.use((req, res, next) => {
// modify the request object
req.customProperty = "Hello, world!";
// call the next middleware
next();
});
In the example above, we define a middleware that adds a new customProperty
property to the request object.
Another important feature of Express.js
is routing. Routing allows us to map incoming requests to specific functions or middleware. To add a route to an Express.js
application, we use the get
, post
, put
, delete
, or all
method of the Application
class:
app.get("/", (req, res) => {
res.send("Hello, world!");
});
In the example above, we define a route that responds with the text "Hello, world!" when an HTTP GET request is sent to the root URL ("/").
In this introduction, we learned how to import the Application
class from Express.js
and use it to create instances of an Express.js
application, add middleware to the application, and add routes to the application. These are just a few of the many features provided by Express.js
.