在Next.js 13服务器组件中访问域名和完整路径

huangapple go评论34阅读模式
英文:

Access domain & full path in next.js 13 server component

问题

如何在Next.js 13中使用app目录的服务器组件中访问域名和完整路径?在以前的Next.js版本(如版本12)中,我可以在getServerSideProps函数中使用上下文来实现这一点,但在app目录中不再支持此功能。

我有一个小型的SaaS应用程序,不同的域可以指向相同的Next.js代码,通过传递域名和路径名,我可以获取该特定帐户的API数据,就像WordPress多站点一样。

在Next.js 13中的app目录中是否有更好的方法来实现这一点?请帮忙。

英文:

How can I access the domain name and full path in a server component in Next.js 13 using the app directory? In previous versions of Next.js (such as version 12), I could do this using context in the getServerSideProps function, but this is no longer supported in the app directory.

I have a small SaaS app where different domains can point to the same Next.js code, and by passing the domain and pathname, I can get data from the API for that particular account, same like WordPress multisite I think.

Is there a better way to do this in Next.js 13 with the app directory? Please help.

答案1

得分: 7

以下是翻译好的部分:

import { headers } from 'next/headers';

export default function Home() {
  const headersList = headers();
  
  headersList.get('host'); // 获取域名
  headersList.get('next-url'); // 获取URL

  return <div>....</div>;
}
英文:

You can do something like this :

import { headers } from &#39;next/headers&#39;;

export default function Home() {
  const headersList = headers();
  
  headersList.get(&#39;host&#39;); // to get domain
  headersList.get(&#39;next-url&#39;); // to get url

  return &lt;div&gt;....&lt;/div&gt;
}

huangapple
  • 本文由 发表于 2023年4月17日 02:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定