如何在 NextJs 项目中获取页面 URL 或主机名? [英] How to get page URL or hostname in NextJs Project?

查看:30
本文介绍了如何在 NextJs 项目中获取页面 URL 或主机名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在静态站点生成器上获取页面的完整 URL 或站点主机名,如下图所示.

I want to get the page's full URL or site hostname like the image below on Static Site Generator.

我会尝试使用 window.location.hostname,但它不起作用.

I will try with window.location.hostname, but it doesn't work.

错误:未定义窗口.

推荐答案

如果你想要服务器端getInitialProps里面的主机名,你仍然可以从req中得到它

If you want the hostname inside getInitialProps on server side, still you can get it from req

Home.getInitialProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }

这篇关于如何在 NextJs 项目中获取页面 URL 或主机名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆