KoaJS教程

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 时,我们得到-
重定向你好
如果我们导航到任何其他路线,我们会得到-
重定向错误
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4