Express.js 是一個最小且靈活的 Node.js Web 應用程式框架,為 Web 和行動應用程式提供了一組強大的功能。它簡化了伺服器端應用程式和 API 的建置、HTTP 請求的處理以及中間件的管理。
安裝與設定 Express.js 的步驟:
安裝 Node.js:
建立一個新的專案目錄:
mkdir my-express-app cd my-express-app
npm init -y
此指令使用預設設定建立一個 package.json 檔案。
npm install express
此命令安裝 Express.js 並將其新增為 package.json 檔案中的依賴項。
npm install --save-dev nodemon
"scripts": { "start": "nodemon app.js" }
設定 JavaScript 導入語法:
"type": "module"
建立入口點檔案:
在專案目錄中建立一個名為 app.js(或 index.js)的檔案。此檔案將包含您的 Express 應用程式程式碼。
要建立基本的 Express 應用程序,請按照以下步驟操作:
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
運行應用程式:
npm start
透過這些步驟,您已經使用 ES6 導入語法設定了一個基本的 Express.js 應用程序,並將 Nodemon 配置為在開發過程中自動重新啟動伺服器。此設定有助於簡化開發並有效處理程式碼變更。
Express.js 中的路由是定義應用程式如何回應特定端點的客戶端請求的過程。可以為不同的 HTTP 方法(GET、POST、PUT、DELETE 等)定義路由,並且可以組織處理複雜的 URL 結構。
GET 路由用於從伺服器檢索資料。它通常用於根據查詢提供靜態內容或資料。
範例:
// Basic GET route app.get('/home', (req, res) => { res.send('Welcome to the Home Page!'); });
POST 路由用於將資料傳送到伺服器。它通常用於提交表單或建立新資源。
範例:
// Basic POST route app.post('/submit', (req, res) => { res.send('Form submitted!'); });
PUT 路由用於更新伺服器上的現有資料。它通常用於修改資源或更新記錄。
範例:
// Basic PUT route app.put('/update', (req, res) => { res.send('Data updated!'); });
DELETE 路由用於從伺服器中刪除資料。用於刪除資源或記錄。
範例:
// Basic DELETE route app.delete('/delete', (req, res) => { res.send('Data deleted!'); });
Express.js 中的 app.use 方法用於註冊處理請求的中間件函數。中間件函數依照定義的順序執行,app.use 可用於全域應用中介軟體或特定路徑。
當在沒有路徑的情況下使用 app.use 時,中介軟體功能將套用於所有傳入請求。這對於設定全域功能(例如日誌記錄、解析請求正文或處理會話)非常有用。
範例:
// Middleware function applied globally app.use((req, res, next) => { console.log(`Request URL: ${req.url}`); next(); // Pass control to the next handler }); app.get('/', (req, res) => { res.send('Home Page'); });
You can use app.use to apply middleware only to requests that match a specific path. This allows you to target middleware to certain routes.
Example:
// Middleware function applied to /admin paths app.use('/admin', (req, res, next) => { console.log('Admin route accessed'); next(); // Pass control to the next handler }); app.get('/admin/dashboard', (req, res) => { res.send('Admin Dashboard'); }); app.get('/user/profile', (req, res) => { res.send('User Profile'); });
You can chain multiple middleware functions together with app.use, allowing for sequential processing of requests.
Example:
// First middleware function const firstMiddleware = (req, res, next) => { console.log('First Middleware'); next(); // Proceed to the next middleware }; // Second middleware function const secondMiddleware = (req, res, next) => { console.log('Second Middleware'); next(); // Proceed to the next handler }; // Apply multiple middleware functions app.use(firstMiddleware, secondMiddleware); app.get('/', (req, res) => { res.send('Home Page'); });
The app.use method in Express.js provides flexibility for applying middleware functions globally or to specific routes, and for processing requests in a modular fashion.
In Express.js, callback functions are crucial for handling HTTP requests. They are used in middleware and route handlers to process requests and manage responses.
Callback functions in Express.js receive three parameters:
Example:
function callback(req, res, next) { // Your code here next(); // Pass control to the next middleware or route handler }
Middleware functions process requests before they reach route handlers. They utilize the req, res, and next parameters.
Example:
const logMiddleware = (req, res, next) => { console.log(`Request URL: ${req.url}`); next(); // Pass control to the next handler }; app.use(logMiddleware); // Apply middleware globally app.get('/', (req, res) => { res.send('Home Page'); });
Route handlers define responses for specific routes, using callback parameters to manage requests and responses.
Example:
app.get('/example', (req, res) => { res.send('Hello World!'); });
Multiple middleware functions can be chained together to handle requests sequentially.
Example:
const authenticate = (req, res, next) => { console.log('Authentication middleware'); next(); // Proceed to the next middleware }; const authorize = (req, res, next) => { console.log('Authorization middleware'); next(); // Proceed to the route handler }; app.get('/profile', authenticate, authorize, (req, res) => { res.send('User Profile'); });
Route parameters are dynamic segments of a URL used to capture values from the URL path. They allow you to define routes that can handle variable input, making your routes more flexible.
Route parameters are defined in the route path by using a colon : followed by the parameter name. You can access these parameters in your route handler through the req.params object.
Example:
// Route with a route parameter app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
You can define multiple route parameters in a single route path, allowing for more complex URL structures.
Example:
// Route with multiple route parameters app.get('/post/:year/:month/:day', (req, res) => { const { year, month, day } = req.params; res.send(`Post date: ${year}-${month}-${day}`); });
Route parameters can also be optional. Use a question mark ? to indicate optional segments in the route path.
Example:
// Route with an optional route parameter app.get('/product/:id?', (req, res) => { const productId = req.params.id || 'not specified'; res.send(`Product ID: ${productId}`); });
Route parameters provide a way to build dynamic and flexible routes in Express.js, allowing you to handle various input values and create more sophisticated URL patterns.
In Express.js, the req object represents the incoming HTTP request from the client. It includes details about the request such as URL, headers, and body. Properly understanding the req object is crucial for handling requests effectively.
The req.body property contains data sent in the request body, typically used in POST and PUT requests. To access req.body, you need to use middleware for parsing the request data.
Handling JSON Data:
app.use(express.json()); // Middleware to parse JSON bodies app.post('/submit', (req, res) => { const { name, age } = req.body; res.send(`Received data - Name: ${name}, Age: ${age}`); });
Handling URL-encoded Data:
app.use(express.urlencoded({ extended: true })); // Middleware to parse URL-encoded bodies app.post('/submit', (req, res) => { const { name, age } = req.body; res.send(`Received data - Name: ${name}, Age: ${age}`); });
The req.cookies property contains cookies sent by the client. To use req.cookies, you need the cookie-parser middleware to parse cookies in requests.
Example:
import cookieParser from 'cookie-parser'; app.use(cookieParser()); // Middleware to parse cookies app.get('/check-cookies', (req, res) => { const user = req.cookies.user; // Access a cookie named 'user' res.send(`Cookie value - User: ${user}`); });
The req.method property contains the HTTP method of the incoming request. This can be useful for handling different types of requests, such as GET, POST, PUT, DELETE, etc.
Example:
app.use((req, res, next) => { console.log(`Request Method: ${req.method}`); // Logs the HTTP method of the request next(); // Pass control to the next handler }); app.get('/example', (req, res) => { res.send(`This is a GET request`); }); app.post('/example', (req, res) => { res.send(`This is a POST request`); });
The req.params property contains route parameters specified in the URL path. Route parameters are used to capture values from the URL and are typically defined in routes with a colon syntax (e.g., /users/:id).
Example:
app.get('/users/:id', (req, res) => { const userId = req.params.id; // Access the route parameter 'id' res.send(`User ID: ${userId}`); });
The req.query property contains query string parameters from the URL. These are typically used to pass data in the URL for GET requests.
Example:
app.get('/search', (req, res) => { const query = req.query.q; // Access the query parameter 'q' res.send(`Search query: ${query}`); });
The req.get() method is used to retrieve HTTP headers from the incoming request. It allows you to access specific headers by name. This is useful for extracting metadata about the request or for handling custom headers.
Example:
app.get('/headers', (req, res) => { const userAgent = req.get('User-Agent'); // Access the 'User-Agent' header const host = req.get('Host'); // Access the 'Host' header const acceptLanguage = req.get('Accept-Language'); // Access the 'Accept-Language' header const contentType = req.get('Content-Type'); // Access the 'Content-Type' header res.send(` User-Agent: ${userAgent}<br> Host: ${host}<br> Accept-Language: ${acceptLanguage}<br> Content-Type: ${contentType} `); });
In Express.js, the res object represents the HTTP response that is sent back to the client. It is used to set response headers, status codes, and to send data or files back to the client. Understanding the res object is essential for controlling the response sent from the server.
The res.append() method is used to add additional headers to the response. It is useful when you need to modify or add headers dynamically before sending the response.
Example:
app.get('/set-headers', (req, res) => { res.append('Custom-Header', 'HeaderValue'); // Add a custom header res.append('Another-Header', 'AnotherValue'); // Add another header res.send('Headers have been set!'); });
The res.cookie() method is used to set cookies on the client's browser. It allows you to send cookies with specific options such as expiration, path, and secure flags.
Example:
app.get('/set-cookie', (req, res) => { // Set a cookie named 'username' with a value 'JohnDoe' res.cookie('username', 'JohnDoe', { maxAge: 24 * 60 * 60 * 1000, // Cookie expires after 1 day httpOnly: true, // Cookie is not accessible via JavaScript secure: false, // Cookie is sent over HTTP (not HTTPS) path: '/' // Cookie is valid for the entire domain }); res.send('Cookie has been set'); });
The res.end() method is used to end the response process and send the response to the client. It is often used to send the final output or to close the response stream when no additional data needs to be sent.
Example:
app.get('/finish', (req, res) => { res.end('Response has been sent and the connection is closed.'); });
The res.json() method is used to send a JSON response to the client. It automatically sets the Content-Type header to application/json and converts the provided data into a JSON string.
Example:
app.get('/data', (req, res) => { const data = { name: 'John Doe', age: 30, city: 'New York' }; res.json(data); });
The res.location() method sets the Location header of the response. It is commonly used to specify the URL to which a client should be redirected. However, this method does not send a response to the client by itself; it only sets the header.
Example:
app.get('/set-location', (req, res) => { res.location('/new-url'); res.send('Location header has been set'); });
The res.redirect() method sends a redirect response to the client. It sets the Location header and sends a status code (default is 302) to redirect the client to a different URL.
Example:
app.get('/redirect', (req, res) => { res.redirect('/new-url'); });
The res.send() method is used to send a response to the client. It can send a variety of response types, including strings, buffers, objects, or arrays. The method automatically sets the Content-Type header based on the type of the response.
Example:
app.get('/text', (req, res) => { res.send('This is a plain text response.'); }); app.get('/json', (req, res) => { const data = { message: 'This is a JSON response.' }; res.send(data); }); app.get('/buffer', (req, res) => { const buffer = Buffer.from('This is a buffer response.'); res.send(buffer); });
The res.sendFile() method is used to send a file as the response to the client. It sets the appropriate Content-Type header based on the file type and streams the file to the client.
Example:
import path from 'path'; app.get('/file', (req, res) => { const filePath = path.join(__dirname, 'public', 'example.txt'); res.sendFile(filePath); });
The res.sendStatus() method sets the HTTP status code and sends the corresponding status message as the response body. It is a shorthand for setting the status code and sending a response in one step.
Example:
app.get('/status', (req, res) => { res.sendStatus(404); // Sends a 404 Not Found status with the message 'Not Found' });
The res.set() method sets HTTP headers for the response. It can be used to specify various headers, including custom headers.
Example:
app.get('/headers', (req, res) => { res.set('X-Custom-Header', 'Value'); res.set({ 'Content-Type': 'application/json', 'X-Another-Header': 'AnotherValue' }); res.send('Headers set'); });
The res.status() method sets the HTTP status code for the response. This method is used to define the status code before sending the response.
Example:
app.get('/error', (req, res) => { res.status(500).send('Internal Server Error'); // Sets status code to 500 and sends the message });
以上是Express.js 完整指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!