Express.js 作为一个简约灵活的 Node.js 网络应用框架崭露头角,为构建单页、多页和混合型 Web 应用提供了一套强大的功能。本文作为一个实用指南,教你如何利用 Express.js 简化开发流程。
开始准备 🚀
在深入代码之前,首先简单设置环境:
sh
echo 'content in sample.txt' >> sample.txt
mkdir test && cd test && npm init -y && npm i cors express
通过上面的代码就初始化了一个新的 Node.js 项目,并安装了两个必要的中间件包:cors
和 express
。
启动服务器 🌐
配置好环境后,在 6666 端口实例化了一个服务器:
javascript
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 6666;
app.use(cors());
使用 cors
中间件来启用跨源资源共享,允许从其他域请求资源。
成功路由 🛣️
Express.js 的路由功能非常强大。例如,建立了一个简单的 new-url
路由:
javascript
app.get('/new-url', (req, res) => {
res.status(304).send('这是重定向后的新 URL 页面。');
});
返回了 304
状态码,表示资源未被修改。
促进用户互动 🤝
为了与用户互动,像 /user
这样的路由返回了 JSON 数据:
javascript
app.get('/user', (req, res) => {
res.json(userData);
});
自动设置 application/json
的内容类型,简化了响应过程。
增强文件可访问性 📁
Express.js 还简化了文件下载。定义了一个路由来提示用户下载 sample.txt
,并适当设置了 Content-Disposition
头信息:
javascript
app.get('/download', (req, res) => {
res.download(path.join(__dirname, 'sample.txt'));
});
处理错误和未授权访问 🔐
错误处理至关重要。像 /not-found
和 /unauthorized
这样的路由展示了使用状态码来适当地通知客户端:
javascript
app.get('/not-found', (req, res) => {
res.status(404).json({ message: '资源未找到' });
});
app.get('/unauthorized', (req, res) => {
res.status(401).send('未授权访问');
});
提供静态文件和图片 🖼️
Express.js 轻松地提供静态文件和图片服务,设置了正确的 Content-Type
头信息,比如 /sendfile
路由:
javascript
app.get('/sendfile', (req, res) => {
res.sendFile(path.join(__dirname, '70.jpg'));
});
管理 Cookies 🍪
此外,管理 Cookies 非常简单。/cookie
路由展示了设置 Cookie 并发送响应流的过程:
javascript
app.get('/cookie', (req, res) => {
res.cookie('foo', 'bar');
res.write('写入了新的 Cookie');
res.end();
});
结论 📝
Express.js 的高效之处在于其简单性和灵活性,使其成为现代 Web 开发者不可或缺的工具。通过遵循这个实用指南,你可以快速建立一个强大的服务器,处理各种路由,管理文件,并处理客户端互动,同时保持代码库的整洁和可维护性。
附录:完整代码清单 📃
以下是伴随上述文章的完整代码。该代码演示了如何使用 Express.js 的各种方法来创建一个简单
的 Web 服务器,该服务器能够处理各种路由和功能。
javascript
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const PORT = 6666;
// Simulated data for demonstration purposes
const userData = {
id: 1,
name: 'John Doe',
email: 'john@example.com'
};
// Enabling Cross-Origin Resource Sharing
app.use(cors());
// Route for the new URL page
app.get('/new-url', (req, res) => {
res.status(304).send('This is the new URL page after redirection.');
});
// Route to redirect to the new URL page
app.get('/redirect', (req, res) => {
res.redirect('/new-url');
});
// Route for 404 Not Found
app.get('/not-found', (req, res) => {
res.status(404).json({ message: 'Resource not found' });
});
// Route for 401 Unauthorized
app.get('/unauthorized', (req, res) => {
res.status(401).send('Unauthorized access');
});
// Home page route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js Demo!');
});
// User data route
app.get('/user', (req, res) => {
res.json(userData);
});
// File download route
app.get('/download', (req, res) => {
res.download(path.join(__dirname, 'sample.txt'));
});
// Failed attempt to use res.render without a view engine
app.get('/about', (req, res) => {
res.render('<h1>About</h1>');
});
// Route for sending status code using res.sendStatus
app.get('/error', (req, res) => {
res.sendStatus(404);
});
// Route for JSONP support
app.get('/jsonp', (req, res) => {
res.jsonp(userData);
});
// Route to end the response
app.get('/end', (req, res) => {
res.end();
});
// Route to send a file
app.get('/sendfile', (req, res) => {
res.sendFile(path.join(__dirname, 'image.jpg'));
});
// Route for setting a cookie and sending a response stream
app.get('/cookie', (req, res) => {
res.cookie('foo', 'bar');
res.write('write a new cookie');
res.end();
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
此代码为文章提供了完整的参考,提供了如何利用 Express.js 不同的响应方法来创建能够处理各种 Web 路由和功能的 Web 服务器的实际示例。请注意,某些路由,如 '/about' 路由,旨在展示某些误用或错误。
English version: Streamlining Web Development with Express.js: A Practical Guide
In the bustling landscape of web development, Express.js emerges as a minimalist and flexible Node.js web application framework, providing a robust set of features for building single-page, multi-page, and hybrid web applications. Here's a practical guide on harnessing Express.js to streamline your development process.
Getting Started
Before diving into the code, one prepares the environment with a simple setup:
sh
echo 'content in sample.txt' >> sample.txt
mkdir test && cd test && npm init -y && npm i cors express
This initializes a new Node.js project and installs two essential middleware packages: cors
and express
.
Launching the Server
Upon setting up the environment, a server is instantiated on port 6666:
javascript
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 6666;
app.use(cors());
The cors
middleware is employed to enable Cross-Origin Resource Sharing, allowing resources to be requested from another domain.
Routing to Success
Express.js thrives on its routing capabilities. For instance, a simple route to a new-url
is established:
javascript
app.get('/new-url', (req, res) => {
res.status(304).send('This is the new URL page after redirection.');
});
A 304
status code is returned, indicating that the resource has not been modified.
Facilitating User Interaction
To interact with users, routes like /user
return JSON data:
javascript
app.get('/user', (req, res) => {
res.json(userData);
});
A content type of application/json
is automatically set, streamlining the response process.
Enhancing File Accessibility
Express.js also simplifies file downloads. A route is defined to prompt the user to download sample.txt
, with the Content-Disposition
header set appropriately:
javascript
app.get('/download', (req, res) => {
res.download(path.join(__dirname, 'sample.txt'));
});
Addressing Errors and Unauthorized Access
Error handling is crucial. Routes like /not-found
and /unauthorized
showcase the use of status codes to inform the client appropriately:
javascript
app.get('/not-found', (req, res) => {
res.status(404).json({ message: 'Resource not found' });
});
app.get('/unauthorized', (req, res) => {
res.status(401).send('Unauthorized access');
});
Serving Static Files and Images
Express.js effortlessly serves static files and images, setting the correct Content-Type
headers, such as for the route /sendfile
:
javascript
app.get('/sendfile', (req, res) => {
res.sendFile(path.join(__dirname, '70.jpg'));
});
Managing Cookies
Additionally, managing cookies is a breeze. The /cookie
route demonstrates setting a cookie and sending a response stream:
javascript
app.get('/cookie', (req, res) => {
res.cookie('foo', 'bar');
res.write('write a new cookie');
res.end();
});
Conclusion
Express.js's efficiency lies in its simplicity and flexibility, making it an indispensable tool for modern web developers. By following this practical guide, you can quickly establish a robust server, handle various routes, manage files, and deal with client interactions, all while maintaining a clean and maintainable codebase.
Appendix: Complete Code Listing
The following is the complete code that accompanies the article above. This code demonstrates the use of various Express.js methods to create a simple web server that handles a variety of routes and functionalities.
javascript
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const PORT = 6666;
// Simulated data for demonstration purposes
const userData = {
id: 1,
name: 'John Doe',
email: 'john@example.com'
};
// Enabling Cross-Origin Resource Sharing
app.use(cors());
// Route for the new URL page
app.get('/new-url', (req, res) => {
res.status(304).send('This is the new URL page after redirection.');
});
// Route to redirect to the new URL page
app.get('/redirect', (req, res) => {
res.redirect('/new-url');
});
// Route for 404 Not Found
app.get('/not-found', (req, res) => {
res.status(404).json({ message: 'Resource not found' });
});
// Route for 401 Unauthorized
app.get('/unauthorized', (req, res) => {
res.status(401).send('Unauthorized access');
});
// Home page route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js Demo!');
});
// User data route
app.get('/user', (req, res) => {
res.json(userData);
});
// File download route
app.get('/download', (req, res) => {
res.download(path.join(__dirname, 'sample.txt'));
});
// Failed attempt to use res.render without a view engine
app.get('/about', (req, res) => {
res.render('<h1>About</h1>');
});
// Route for sending status code using res.sendStatus
app.get('/error', (req, res) => {
res.sendStatus(404);
});
// Route for JSONP support
app.get('/jsonp', (req, res) => {
res.jsonp(userData);
});
// Route to end the response
app.get('/end', (req, res) => {
res.end();
});
// Route to send a file
app.get('/sendfile', (req, res) => {
res.sendFile(path.join(__dirname, 'image.jpg'));
});
// Route for setting a cookie and sending a response stream
app.get('/cookie', (req, res) => {
res.cookie('foo', 'bar');
res.write('write a new cookie');
res.end();
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This code serves as a complete reference for the article, providing practical examples of how to utilize different response methods in Express.js to create a web server capable of handling various web routes and functionalities. Please note that some routes, such as the '/about' route, are intended to demonstrate certain misuses or errors for educational purposes.