请求上下文类
| 函数 | 用途 | SSR | 客户端 |
|---|---|---|---|
useRequestURL | 获取请求 URL | ✅ | ✅ |
useRequestHeaders | 获取请求头 | ✅ | ❌ 返回空 |
useRequestEvent | 获取 H3 事件对象 | ✅ | ❌ 返回 null |
useRequestFetch | 获取带上下文的 $fetch | ✅ | ❌ |
请求上下文类函数主要用于 SSR 场景
在客户端大多返回空值或不可用。
useRequestURL
获取当前请求的完整 URL,SSR 和客户端都可用。
ts
const url = useRequestURL()
url.href // 'https://example.com/path?q=nuxt'
url.origin // 'https://example.com'
url.protocol // 'https:'
url.host // 'example.com'
url.hostname // 'example.com'
url.port // ''
url.pathname // '/path'
url.search // '?q=nuxt'
url.searchParams // URLSearchParams 对象典型场景
生成 canonical URL、OG URL。
ts
const url = useRequestURL()
useSeoMeta({ ogUrl: () => url.href })useRequestHeaders
获取请求头,仅在 SSR 时有效。
ts
// 获取所有请求头
const headers = useRequestHeaders()
// 获取指定请求头
const { host, cookie } = useRequestHeaders(['host', 'cookie'])典型场景
在 SSR 时转发客户端的请求头(如 Cookie)给 API。
ts
// 服务端获取客户端 Cookie
const { cookie } = useRequestHeaders(['cookie'])
// 转发给内部 API
const data = await $fetch('/api/data', {
headers: { cookie },
})INFO
️ 客户端调用返回空对象 不要依赖客户端的返回值
useRequestEvent
获取 H3 事件对象,仅在服务端有效。
ts
const event = useRequestEvent()
if (event) {
const url = getRequestURL(event)
const cookies = parseCookies(event)
const headers = getRequestHeaders(event)
}useRequestEvent 的用途
- 在组件中访问请求上下文(如 cookies、headers)
- 转发请求信息给 API
INFO
️ 客户端调用返回 null 使用时必须做 null 检查
useRequestFetch
获取带请求上下文的 $fetch,仅在 SSR 时有效。
ts
const $fetch = useRequestFetch()
// 请求会携带当前请求的上下文和头信息
const data = await $fetch('/api/data')useRequestFetch vs $fetch
useRequestFetch:SSR 时转发请求头(如 Cookie、Authorization)$fetch:不转发上下文
在 SSR 时需要转发请求上下文的场景
用 useRequestFetch 。