目录

Koa.js - 重定向( Redirects)

创建网站时,重定向非常重要。 如果请求格式错误的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 ,我们得到 -

重定向你好

如果我们导航到任何其他路线,我们得到 -

重定向错误
↑回到顶部↑
WIKI教程 @2018