Appearance
尾部斜杠中间件
🌐 Trailing Slash Middleware
此中间件处理 GET 请求中 URL 中的尾部斜杠。
🌐 This middleware handles Trailing Slash in the URL on a GET request.
appendTrailingSlash 会将 URL 重定向到它添加了尾部斜杠的地址,如果内容未找到。同时,trimTrailingSlash 会移除尾部斜杠。
导入
🌐 Import
ts
import { Hono } from 'hono'
import {
appendTrailingSlash,
trimTrailingSlash,
} from 'hono/trailing-slash'用法
🌐 Usage
/about/me 的 GET 请求重定向到 /about/me/ 的示例。
🌐 Example of redirecting a GET request of /about/me to /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 的示例。
🌐 Example of redirecting a GET request of /about/me/ to /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'))选项
🌐 Options
optional 总是重定向: boolean
默认情况下,尾部斜杠中间件只有在响应状态为 404 时才会重定向。当 alwaysRedirect 设置为 true 时,中间件会在执行处理程序之前进行重定向。这对于默认行为无效的通配符路由(*)非常有用。
🌐 By default, trailing slash middleware only redirects when the response status is 404. When alwaysRedirect is set to true, the middleware redirects before executing handlers. This is useful for wildcard routes (*) where the default behavior doesn't work.
ts
const app = new Hono()
app.use(trimTrailingSlash({ alwaysRedirect: true }))
app.get('/my-path/*', (c) => c.text('Wildcard route'))此选项适用于 trimTrailingSlash 和 appendTrailingSlash。
🌐 This option is available for both trimTrailingSlash and appendTrailingSlash.
optional 跳过: (path: string) => boolean
一个函数,用于根据请求路径确定是否应跳过重定向。如果函数返回 true,则将跳过重定向。当你想要排除某些路径(例如具有文件扩展名的路径)不被重定向时,这非常有用。
🌐 A function that determines whether the redirect should be skipped based on the request path. If the function returns true, the redirect will be skipped. This is useful when you want to exclude certain paths, such as those with file extensions, from being redirected.
ts
app.use(
appendTrailingSlash({
skip: (path) => /\.\w+$/.test(path),
})
)此选项适用于 trimTrailingSlash 和 appendTrailingSlash。
🌐 This option is available for both trimTrailingSlash and appendTrailingSlash.
注意
🌐 Note
当请求方法为 GET 且响应状态为 404 时,它将被启用。
🌐 It will be enabled when the request method is GET and the response status is 404.