LoginSignup
3
1

More than 3 years have passed since last update.

TypeScript: Koaでリダイレクトする

Posted at

本稿ではTypeScriptでKoaのリダイレクトをする方法を説明する。

Koaでのリダイレクトのしかた

ハンドラーに渡ってくるctxオブジェクトにredirect()メソッドが生えているので、それを叩くだけ。

ctx.redirect(url)

ctx.redirectの使用例

import Koa from "koa";
import _ from "koa-route";

const app = new Koa()
app.use(_.get('/old', async ctx => {
    ctx.redirect('/new')
}))
app.use(_.get('/new', async ctx => {
    ctx.body = 'redirected!'
}))

app.listen(4000)

/oldへのHTTPリクエスト

GET /old HTTP/1.1
Host: localhost:4000

レスポンスは302になり、Locationヘッダにリダイレクト先のURLがセットされているのがわかる。

HTTP/1.1 302 Found
Connection: keep-alive
Content-Length: 39
Content-Type: text/html; charset=utf-8
Date: Mon, 02 Sep 2019 06:01:51 GMT
Location: /new

Redirecting to <a href="/new">/new</a>.

参考文献

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1