第3章 Express 的请求与响应(二)

2 设置响应数据

在 Express 中,可以通过 res 对象设置 HTTP 响应。常见的响应方法包括 res.send、res.json、res.status、res.sendFile 等。

2.1 发送文本和 JSON 响应

发送文本响应:

javascript 复制代码
app.get('/text', (req, res) => {
    res.send('Hello, world!');
});

发送 JSON 响应:

javascript 复制代码
app.get('/json', (req, res) => {
    const data = { message: 'Hello, world!' };
    res.json(data);
});

代码详解:

  • res.send('Text'):发送文本响应。
  • res.json({ key: 'value' }):发送 JSON 响应。
2.2 设置响应状态码

可以通过 res.status 方法设置 HTTP 响应状态码。

示例:

javascript 复制代码
app.get('/not-found', (req, res) => {
    res.status(404).send('Resource not found');
});

代码详解:

  • res.status(404).send('Message'):设置响应状态码为 404,并发送响应消息。
2.3 发送文件

可以通过 res.sendFile 方法发送文件作为响应。

示例:

javascript 复制代码
const path = require('path');

app.get('/file', (req, res) => {
    const filePath = path.join(__dirname, 'public', 'example.txt');
    res.sendFile(filePath);
});

代码详解:

  • res.sendFile(filePath):发送文件作为响应。
3 处理表单数据

处理表单数据是 Web 应用程序的常见需求。通常使用 POST 请求发送表单数据,并使用中间件解析请求体。

示例:

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Form</title>
</head>
<body>
    <form action="/submit-form" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

服务器端代码:

javascript 复制代码
app.use(express.urlencoded({ extended: true }));

app.post('/submit-form', (req, res) => {
    // 获取表单数据
    const name = req.body.name;
    res.send(`Form submitted! Name: ${name}`);
});

代码详解:

  • express.urlencoded({ extended: true }):解析 URL 编码的请求体,将结果存储在 req.body。
  • req.body.name:访问表单数据中的 name 字段。
4 使用查询参数

查询参数是 URL 中的键值对,通常用于传递额外的数据。可以通过 req.query 访问查询参数。

示例:

javascript 复制代码
app.get('/search', (req, res) => {
    const term = req.query.term;
    const sort = req.query.sort;
    res.send(`Search term: ${term}, Sort order: ${sort}`);
});

当用户访问 /search?term=express&sort=desc 时,响应内容将为 "Search term: express, Sort order: desc"。

代码详解:

  • req.query:获取查询参数,返回一个对象。
5 处理文件上传

处理文件上传是许多 Web 应用程序的重要功能。可以使用 multer 中间件处理文件上传。

安装 multer:

bash 复制代码
npm install multer --save

配置 multer:

javascript 复制代码
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
    const file = req.file;
    res.send(`File uploaded: ${file.originalname}`);
});

代码详解:

  • multer({ dest: 'uploads/' }):配置 multer,将上传的文件保存到 uploads 目录。
  • upload.single('file'):处理单个文件上传,file 是表单字段的名称。
  • req.file:访问上传的文件信息。

HTML 表单示例:

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <form action="/upload" method="POST" enctype="multipart/form-data">
        <label for="file">Choose file:</label>
        <input type="file" id="file" name="file">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

通过本章内容,读者应该能够理解并掌握如何在 Express 中处理 HTTP 请求和响应,包括解析请求数据、设置响应数据、处理表单数据、使用查询参数和处理文件上传。这些知识是开发功能丰富的 Web 应用程序的基础。

相关推荐
星光开发者8 天前
基于springboot智慧草场牛羊管理系统-计算机毕设【课程设计】50360
vue.js·spring boot·后端·mysql·php·课程设计·express
vx_Biye_Design12 天前
django房屋租赁推荐系统78455-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·express
vx_Biye_Design15 天前
PHP中医养生馆预约系统60841-计算机课程设计、毕业设计
vue.js·spring boot·后端·mysql·php·课程设计·express
夏幻灵16 天前
Express 静态资源托管详解:从本地 HTML 到 express.static()
前端·html·express
毕业设计70319 天前
(免费领源码)基于node的学生公寓管理系统06412- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
vue.js·mysql·node.js·maven·mybatis·express·b/s
Wx-bishekaifayuan20 天前
springboot桂味美食分享系统40540-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan22 天前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游
Wx-bishekaifayuan22 天前
springboot汉中旅游服务平台41442-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan22 天前
springboot公考微信小程序35511-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan22 天前
springboot线上中医药养生平台管理系统36753-计算机课程设计、毕业设计
java·spring boot·后端·spring·课程设计·express·旅游