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://:3000/hello 時,我們得到 -

Redirect Hello

如果我們導航至任何其他路由,我們得到 -

Redirect Error
廣告