Koa.js - 重定向

创建网站时,重定向非常重要。如果请求的 URL 格式不正确或服务器上存在一些错误,则应将其重定向到相应的错误页面。重定向还可用于阻止人们进入您网站的限制区域。

让我们创建一个错误页面,并在有人请求格式错误的 URL 时重定向到该页面。

var koa = require('koa');
var router = require('koa-router');
var app = koa();
var _ = router();

_.get('/not_found', printErrorMessage);
_.get('/hello', printHelloMessage);

app.use(_.routes());
app.use(handle404Errors);

function *printErrorMessage() {
   this.status = 404;
   this.body = "Sorry we do not have this resource.";
}
function *printHelloMessage() {
   this.status = 200;
   this.body = "Hey there!";
}
function *handle404Errors(next) {
   if (404 != this.status) return;
   this.redirect('/not_found');
}
app.listen(3000);

当我们运行此代码并导航到 /hello 以外的任何路由时,我们将被重定向到 /not_found。我们将中间件放在最后(app.use 函数调用此中间件)。这确保我们最终到达中间件并发送相应的响应。以下是我们运行上述代码时看到的结果。

当我们导航到 https://localhost:3000/hello 时,我们得到 −

Redirect Hello

如果我们导航到任何其他路由,我们将得到 −

Redirect Error