使用 Express.js 简化 Web 开发:实用指南 📘

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 项目,并安装了两个必要的中间件包:corsexpress

启动服务器 🌐

配置好环境后,在 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.

相关推荐
dingdingfish1 天前
关于 Oracle Database Express Edition 的功能和安装
oracle·express·database·vagrant·edition
知难行难3 天前
福昕阅读器高级版解决文件上传IEEE PDF eXpress字体未嵌入
pdf·express
ch_s_t5 天前
基于 Express+JWT + Vue 的前后端分离架构
vue.js·架构·express
caridle6 天前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
胡西风_foxww11 天前
nodejs爬虫系统
爬虫·nodejs·node·系统·express·request·cheerio
松果猿15 天前
场地污染在线计算可视化平台,获得易智瑞GIS开发竞赛C组优胜奖,内附易智瑞GIS开发竞赛与全国大学生测绘学科创新创业智能大赛提交材料。
vue·express
js_user20 天前
在 Vue 渲染模板时,如何保留模板中的 HTML 注释?
开发语言·前端·javascript·css·vue.js·html·express
瑕、疵22 天前
使用Node.js和Express构建RESTful API
node.js·restful·express
js_user24 天前
css中,我想把文章的第一行设置单独的样式
开发语言·前端·javascript·css·node.js·css3·express
傻啦嘿哟1 个月前
Plotly Express 详解:快速创建精美交互式可视化图表的最佳实践
信息可视化·plotly·express