Express 入门指南(四) 请求与响应处理

Express 请求与响应处理入门

一、Request 对象核心方法

获取请求参数

  • req.query:提取 URL 查询参数(如 ?name=John
  • app.get('/user', (req, res) => {
      console.log(req.query); // 输出 { name: "John", age: "25" }
      res.json(req.query);
    });
    
  • req.params:获取路由动态参数(如 /user/:id
  • app.get('/post/:category/:title', (req, res) => {
      console.log(req.params); // 输出 { category: "tech", title: "express" }
      res.json(req.params);
    });
    
  • req.body:解析 POST/PUT 请求体(需配合 body-parser 中间件)

        解析 JSON 请求体
        客户端发送 JSON 数据时(如 Content-Type: application/json):

const express = require('express');
const app = express();
app.use(express.json()); // 内置中间件替代 body-parser

app.post('/api/user', (req, res) => {
  console.log(req.body); // 输出 { name: "John", age: 30 }
  res.send(`用户: ${req.body.name}`);
});

        需通过 express.json() 中间件解析 JSON 格式请求体  

        解析表单数据 

        处理 application/x-www-form-urlencoded 格式的表单提交:

app.use(express.urlencoded({ extended: true })); // 解析 URL-encoded 数据

app.post('/login', (req, res) => {
  console.log(req.body); // 输出 { username: "admin", password: "123" }
  res.json(req.body);
});

  extended: true 支持嵌套对象解析  

请求元数据

  • req.method:获取 HTTP 请求方法(GET/POST 等)
  • app.all('/api', (req, res) => {
      if (req.method === 'GET') {
        res.send('处理GET请求');
      } else if (req.method === 'POST') {
        res.send('处理POST请求');
      }
    });
    
  • req.path:请求路径(不包含查询字符串)
  • app.use('/admin', (req, res, next) => {
      if (req.path === '/dashboard') {
        console.log('访问管理员仪表盘');
      }
      next();
    });
    
  • req.ip / req.hostname:客户端 IP 和主机名

  req.ip 获取客户端 IP 

        基本用法

        返回客户端的 IP 地址(支持代理场景)

app.get('/client-ip', (req, res) => {
  console.log(req.ip); // 输出类似 "::ffff:192.168.1.1"
  res.send(`你的IP: ${req.ip}`);
});

         自动处理 X-Forwarded-For 头(需配置信任代理)

        代理环境配置

        若部署在 Nginx 后,需启用代理信任:

app.set('trust proxy', true); // 信任代理服务器

        req.hostname 获取主机名

        基本用法

        返回请求的主机名(不含端口)  

app.get('/host', (req, res) => {
  console.log(req.hostname); // 如 "example.com"
  res.send(`访问的主机: ${req.hostname}`);
});

        与 req.host 区别

         req.hostname 不包含端口号(如 example.com

   req.host 可能包含端口(如 example.com:3000

        注意事项  

        代理配置‌:req.ip 需配合 app.set('trust proxy', true) 获取真实客户端 IP   

        安全性‌:req.hostname 可能被伪造,需结合其他验证逻辑       

其他实用属性

  • req.cookies:读取客户端 Cookies(需 cookie-parser 中间件)
  • const express = require('express');
    const cookieParser = require('cookie-parser');
    const app = express();
    
    app.use(cookieParser());
    
    app.get('/', (req, res) => {
      console.log(req.cookies); // 输出所有 Cookie 对象
      res.send('Cookie 已读取');
    });
    
  • req.headers:访问请求头信息
  • app.post('/api', (req, res) => {
      const contentType = req.headers['content-type']; // 内容类型
      const authorization = req.headers.authorization; // 认证信息
      res.json({ contentType, authorization });
    });
    

二、Response 对象核心方法 

发送响应内容

  • res.send():自动设置 Content-Type 和状态码(支持文本/JSON/Buffer)
  • app.post('/submit', (req, res) => {
      res.status(201).send('资源创建成功'); // 状态码 201
    });
    
  • res.json():发送 JSON 响应(自动设置 Content-Type: application/json
  • app.post('/create', (req, res) => {
      res.status(201).json({ success: true, message: "资源已创建" });
    });
    
  • res.sendFile():传输文件(如 res.sendFile('image.png')
  • app.get('/pdf', (req, res) => {
      res.sendFile('report.pdf', {
        root: __dirname,
        headers: { 'Content-Type': 'application/pdf' }
      });
    });
    

控制响应流程

  • res.status():设置 HTTP 状态码(如 res.status(404)
  • app.get('/success', (req, res) => {
      res.status(200).send('请求成功');
    });
    
  • res.redirect():重定向到指定 URL(默认状态码 302)
  • app.get('/login', (req, res) => {
      res.redirect('/dashboard'); // 重定向到同域下的 /dashboard
    });
    
  • res.set():设置响应头(如 res.set('Cache-Control', 'no-cache')
  • app.get('/download', (req, res) => {
      res.set({
        'Content-Type': 'text/plain',
        'Cache-Control': 'no-cache'
      }).send('File content');
    });
    

Cookie 操作

  • res.cookie():设置 Cookie(可配置过期时间/域名等)
  • app.get('/secure-cookie', (req, res) => {
      res.cookie('session', 'encrypted_data', {
        secure: true,   // 仅 HTTPS 传输
        httpOnly: true, // 禁止 JavaScript 访问
        sameSite: 'strict'
      }).send('安全 Cookie 已设置');
    });
    
  • res.clearCookie():清除指定 Cookie
  • app.get('/clear-auth', (req, res) => {
      res.clearCookie('token', { path: '/admin', domain: '.example.com' })
         .send('带配置的 Cookie 已清除');
    });
    

三、中间件与路由处理

 ‌路由定义

  • 支持 HTTP 方法(app.get()/app.post() 等)和通配路由(app.all())6
  • 示例:
app.get('/user/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

中间件链式调用

  • 通过 next() 传递控制权(如身份验证/日志记录)7
  • 示例:
app.use((req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next();
});

注意事项

  • 文件上传‌:需使用 multer 中间件处理 multipart/form-data 表单
  • 性能优化‌:避免在中间件中阻塞操作(如同步文件读写)
  • 错误处理‌:需自定义错误中间件捕获异常(app.use((err, req, res, next) => {})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值