Skip to content
📈0️⃣

Koa 路由重定向

在 Koa 中进行路由重定向可以通过以下几种方式实现:

  1. 使用 ctx.redirect(url) 方法:该方法用于将客户端重定向到指定的 url 地址。
javascript
const Koa = require("koa");
const app = new Koa();

app.use(async (ctx) => {
  if (ctx.path === "/oldurl") {
    ctx.redirect("/newurl"); // 重定向到新的页面
  } else {
    ctx.body = "Hello World";
  }
});

app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
  1. 设置响应头 ctx.response.set('Location', url) 和状态码 ctx.response.status = 302:可以手动设置响应头和状态码来实现路由重定向。
javascript
const Koa = require("koa");
const app = new Koa();

app.use(async (ctx) => {
  if (ctx.path === "/oldurl") {
    ctx.response.set("Location", "/newurl");
    ctx.response.status = 302;
  } else {
    ctx.body = "Hello World";
  }
});

app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});

以上两种方式都可以在特定条件下执行路由重定向操作。在示例中,当访问 /oldurl 时,会将客户端重定向到 /newurl