英文:
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 'next/headers';
export default function Home() {
const headersList = headers();
headersList.get('host'); // to get domain
headersList.get('next-url'); // to get url
return <div>....</div>
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论