Trailing Slash 中间件
此中间件处理 GET 请求 URL 中的末尾斜杠。
找不到内容时,appendTrailingSlash 会重定向到添加了末尾斜杠的 URL。trimTrailingSlash 则会移除末尾斜杠。
导入
ts
import { Hono } from 'hono'
import {
appendTrailingSlash,
trimTrailingSlash,
} from 'hono/trailing-slash'用法
将 /about/me 的 GET 请求重定向到 /about/me/ 的示例。
ts
import { Hono } from 'hono'
import { appendTrailingSlash } from 'hono/trailing-slash'
const app = new Hono({ strict: true })
app.use(appendTrailingSlash())
app.get('/about/me/', (c) => c.text('With Trailing Slash'))将 /about/me/ 的 GET 请求重定向到 /about/me 的示例。
ts
import { Hono } from 'hono'
import { trimTrailingSlash } from 'hono/trailing-slash'
const app = new Hono({ strict: true })
app.use(trimTrailingSlash())
app.get('/about/me', (c) => c.text('Without Trailing Slash'))选项
optional alwaysRedirect: boolean
默认情况下,末尾斜杠中间件仅在响应状态为 404 时重定向。将 alwaysRedirect 设为 true 后,会在执行处理器之前重定向。这适用于默认行为无法生效的通配符路由(*)。
ts
const app = new Hono()
app.use(trimTrailingSlash({ alwaysRedirect: true }))
app.get('/my-path/*', (c) => c.text('Wildcard route'))此选项同时适用于 trimTrailingSlash 和 appendTrailingSlash。
optional skip: (path: string) => boolean
根据请求路径决定是否跳过重定向的函数。返回 true 时跳过重定向。需要排除特定路径(例如带文件扩展名的路径)时很有用。
ts
app.use(
appendTrailingSlash({
skip: (path) => /\.\w+$/.test(path),
})
)此选项同时适用于 trimTrailingSlash 和 appendTrailingSlash。
注意
请求方法为 GET 且响应状态为 404 时生效。