express响应设置 以及redirect,download,json.sendFdile

144 阅读1分钟

Express 中常用响应方法 的整理,包括设置响应头、重定向、下载、发送 JSON、发送文件等👇


📤 一、设置响应头与状态码

设置状态码

res.status(404).send('Not Found');

设置响应头

res.set('Content-Type', 'text/plain'); // 设置内容类型
res.set('X-Custom-Header', 'MyValue'); // 自定义头
res.send('响应已设置头信息');

🔁 二、重定向 res.redirect()

// 临时重定向(302)
app.get('/old', (req, res) => {
  res.redirect('/new');
});

// 永久重定向(301)
app.get('/moved', (req, res) => {
  res.redirect(301, '/new-location');
});

💾 三、文件下载 res.download()

app.get('/download', (req, res) => {
  res.download('./files/report.pdf'); // 自动设置 Content-Disposition 为 attachment
});

✅ 会自动触发浏览器下载文件,如果找不到文件,会自动触发错误处理。


📦 四、发送 JSON 数据 res.json()

app.get('/api/user', (req, res) => {
  res.json({ name: 'Tom', age: 18 });
});

✅ 自动设置 Content-Type: application/json,并序列化对象


📄 五、发送静态文件 res.sendFile()

const path = require('path');

app.get('/readme', (req, res) => {
  res.sendFile(path.join(__dirname, 'files/readme.txt'));
});

⚠️ 需要提供绝对路径


🔒 六、附加:常见组合使用

app.get('/example', (req, res) => {
  res
    .status(200)
    .set('X-Powered-By', 'Express')
    .json({ message: 'Success!' });
});

🎁 小结

方法作用
res.send()发送字符串、HTML、Buffer、对象等
res.json()发送 JSON 数据并设置响应头
res.sendFile()发送文件(提供绝对路径)
res.download()提示浏览器下载指定文件
res.redirect()重定向到指定路径
res.status()设置响应状态码
res.set()设置响应头信息