使用 Express 的重定向功能

发布于 2022-07-29 00:14:07 字数 2638 浏览 293 评论 0

res.redirect() 函数 将用户重定向到不同的 URL 状态为 302 的 HTTP 响应 。 然后,HTTP 客户端(浏览器、 Axios 等)将跟随重定向并向新 URL 发送 HTTP 请求,如下所示。

const app = require('express')();

// The `res.redirect()` function sends back an HTTP 302 by default.
// When an HTTP client receives a response with status 302, it will send
// an HTTP request to the URL in the response, in this case `/to`
app.get('/from', (req, res) => {
  res.redirect('/to');
});
app.get('/to', (req, res) => res.send('Hello, World!'));

const server = await app.listen(3000);

const res = await axios.get('http://localhost:3000/from');
// Axios follows the redirect and sends a GET `/to` request, so the
// response will contain the string "Hello, World!"
res.data;

res.redirect() 函数还允许您指定 302 以外的 HTTP 状态。302 状态被视为临时重定向 ,这意味着搜索引擎仍将抓取现有 URL。 如果您想指示 URL 已永久更改,则应发送带有 HTTP 状态 301

const app = require('express')();

app.get('/from', (req, res) => {
  // The optional first parameter to `res.redirect()` is a numeric
  // HTTP status.
  res.redirect(301, '/to');
});
app.get('/to', (req, res) => res.send('Hello, World!'));

const server = await app.listen(3000);

const res = await axios.get('http://localhost:3000/from');
// "Hello, World!"
res.data;

处理 POST 请求

关于应该为 POST 请求使用哪个状态代码存在一些细微差别。
严格来说, 不需要保持相同的方法和正文内容 在重定向时 如果要重定向 POST 请求,则应使用 HTTP 307 替代 HTTP 302,并 HTTP 308 替代 HTTP 301。

const app = require('express')();
// Parser to set `req.body`
app.use(require('body-parser').json());

app.post('/from', (req, res) => {
  res.redirect(307, '/to');
});
app.post('/to', (req, res) => res.send(req.body.message));

const server = await app.listen(3000);

const res = await axios.post('http://localhost:3000/from', {
  message: 'Hello, World!'
});
// "Hello, World!"
res.data;

以下是这些常见重定向状态之间权衡的简要总结。

Tradeoffs between HTTP 301 vs 302 vs 307 vs 308

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
28 人气
更多

推荐作者

qq_VRzBBA45

文章 0 评论 0

痴情

文章 0 评论 0

文章 0 评论 0

Mu.

文章 0 评论 0

凉薄对峙

文章 0 评论 0

不落城

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文