简述express response有哪些常用方法?

参考回答

在 Express 中,responseres)对象提供了多个方法用于向客户端发送 HTTP 响应,以下是一些常用的方法:

  1. res.send():发送响应数据(字符串、对象、Buffer)。
    res.send('Hello World');
    
  2. res.json():发送 JSON 格式的响应。
    res.json({ message: 'Success' });
    
  3. res.status():设置 HTTP 状态码,通常与 res.send()res.json() 结合使用。
    res.status(404).send('Not Found');
    
  4. res.redirect():重定向到另一个 URL。
    res.redirect('/new-page');
    
  5. res.sendFile():发送文件到客户端。
    res.sendFile(__dirname + '/index.html');
    
  6. res.set():设置 HTTP 响应头。
    res.set('Content-Type', 'text/html');
    
  7. res.cookie():设置 Cookie。
    res.cookie('token', '123456', { httpOnly: true });
    

这些方法用于处理不同类型的 HTTP 响应,以满足各种应用场景。


详细讲解与拓展

1. res.send()

  • 作用:用于发送响应数据,可以是 字符串Buffer对象
  • 代码示例:
    app.get('/text', (req, res) => {
      res.send('Hello World'); // 发送字符串
    });
    
    app.get('/object', (req, res) => {
      res.send({ message: 'Hello JSON' }); // 发送对象,效果同 res.json()
    });
    
  • 拓展
    • 如果发送的是对象,Express 会自动转换成 JSON,相当于 res.json()

2. res.json()

  • 作用:专门用于返回 JSON 格式的数据,适用于 API 开发。
  • 代码示例:
    app.get('/data', (req, res) => {
      res.json({ success: true, data: [1, 2, 3] });
    });
    
  • 拓展
    • Express 会自动设置 Content-Type: application/json 头部。

3. res.status()

  • 作用:设置 HTTP 状态码,通常与 res.send()res.json() 结合使用。
  • 代码示例:
    app.get('/not-found', (req, res) => {
      res.status(404).send('Page Not Found');
    });
    
    app.get('/error', (req, res) => {
      res.status(500).json({ error: 'Internal Server Error' });
    });
    
  • 拓展
    • 常见 HTTP 状态码:
    • 200 OK:请求成功
    • 201 Created:资源创建成功
    • 400 Bad Request:客户端请求错误
    • 401 Unauthorized:未授权
    • 404 Not Found:资源不存在
    • 500 Internal Server Error:服务器错误

4. res.redirect()

  • 作用:将客户端重定向到另一个 URL。
  • 代码示例:
    app.get('/old-route', (req, res) => {
      res.redirect('/new-route');
    });
    
    app.get('/google', (req, res) => {
      res.redirect('https://www.google.com');
    });
    
  • 拓展
    • 默认是 302 Found(临时重定向)。
    • 可以使用 res.redirect(301, '/new-route') 设置 301 永久重定向

5. res.sendFile()

  • 作用:向客户端发送文件(如 HTML 页面、图片)。
  • 代码示例:
    app.get('/download', (req, res) => {
      res.sendFile(__dirname + '/files/sample.pdf');
    });
    
  • 拓展
    • 适用于文件下载、网页渲染等场景。

6. res.set()

  • 作用:手动设置 HTTP 头部。
  • 代码示例:
    app.get('/custom-header', (req, res) => {
      res.set('X-Custom-Header', 'CustomValue');
      res.send('Check the response headers');
    });
    
  • 拓展
    • 结合 res.set() 设置 CORS 允许跨域:
      app.use((req, res, next) => {
      res.set('Access-Control-Allow-Origin', '*');
      next();
      });
      

7. res.cookie()

  • 作用:设置 Cookie,常用于用户认证。
  • 代码示例:
    app.get('/set-cookie', (req, res) => {
      res.cookie('username', 'JohnDoe', { httpOnly: true, maxAge: 3600000 });
      res.send('Cookie set');
    });
    
  • 拓展
    • httpOnly: true:防止 JavaScript 访问 Cookie,提升安全性。
    • maxAge 设定 Cookie 过期时间(毫秒)。
    • 删除 Cookie:
      res.clearCookie('username');
      

总结

Express 提供了多种响应方法,涵盖文本、JSON、文件、状态码、重定向、头信息和 Cookie 设置等。合理使用这些方法,可以构建更健壮的 Web 应用和 API。

发表评论

后才能评论