我不能在这里使用 window.location 因为它是 SSR 应用程序。useRouter、useRoute 和 useNuxtApp 也没有域名。nuxtApp.ssrContext 未定义。
export default defineNuxtRouteMiddleware((to: any, from: any) => {
console.log("GET HOST HERE")
})
Run Code Online (Sandbox Code Playgroud)
Dre*_*Dru 14
我只是错过了在获取 nuxtApp.ssrContext 之前检查 process.server 。这是我的问题的答案:
export default defineNuxtRouteMiddleware((to: any, from: any) => {
const nuxtApp = useNuxtApp()
let host = ''
if(process.server) {
// for 3.0.0.rc_vercions: host = nuxtApp.ssrContext.req.headers.host
// UPD 27.01.23:
host = nuxtApp.ssrContext?.event.node.req.headers.host
} else {
host = window.location.host
}
})
Run Code Online (Sandbox Code Playgroud)
use*_*906 14
The helper function useRequestURL() was introduced with the release of v3.5.0 of Nuxt. Getting the current url, the protocol scheme, the host, the hostname and the path is very easy:
const url = useRequestURL()
const currentUrl = url.href // https://example.com:3000/hello-world
const protocol = url.protocol // https:
const host = url.host // example.com:3000
const hostname = url.hostname // example.com
const pathname = url.pathname // /hello-world
Run Code Online (Sandbox Code Playgroud)
or if only the hostname is needed we can access the object property directly:
const hostname = useRequestURL().hostname
Run Code Online (Sandbox Code Playgroud)
Since useRequestURL() works on both server-side and client-side there is no need to check for the process.server. The function returns the familiar URL object which properties with their descriptions can be found in the MDN documentation.
Nuxt have updated their documentation and the description of the useRequestURL() can be found in the Composables section.
| 归档时间: |
|
| 查看次数: |
8722 次 |
| 最近记录: |