如何在NextJs项目中获取页面URL或主机名?
我想在静态站点生成器上获取页面的完整 URL 或站点主机名,如下图所示。
我会尝试使用window.location.hostname,但它不起作用。
错误:窗口未定义。
回答
您访问的地方window确保添加检查,以便代码仅在浏览器上执行,而在 SSG 期间不执行”
if (typeof window !== 'undefined') {
const hostname = window.location.hostname;
}
更新:如果您已指定basePath在next.config.js:
module.exports = {
basePath: 'https://www.example.com/docs',
}
然后使用useRouter,您可以访问基本路径:
import { useRouter } from 'next/router'
function Component() {
const router = useRouter();
console.log({ basePath: router.basePath});
// { basePath: 'https://www.example.com/docs' }
...
}
但是如果你有一个相对的基本路径,那么你可以使用第一种方法
- Face this error https://prnt.sc/vyuuz2
- The `basePath` part does not work as it is just used for shortening the path. You can't use an url there.
回答
如果您想要服务器端 getInitalProps 中的主机名,您仍然可以从 req 中获取它
Home.getInitalProps = async(context) => {
const { req, query, res, asPath, pathname } = context;
if (req) {
let host = req.headers.host // will give you localhost:3000
}
}
- It gives an error on build time https://prnt.sc/vyut51