这几乎直接来自 Next.js 站点上的一些示例。
function HomePage(props) {
return (
<div>
<p>Welcome to {props.data.name} Next.js!</p>
<img src="/conexon-logo-white.png" alt="my image" />
</div>
);
}
// This gets called on every request
export async function getServerSideProps(context) {
const res = await fetch('http://localhost:3000/api/test');
const data = await res.json();
// Pass data to the page via props
return { props: { data } };
}
export default HomePage;
当然,该代码在本地运行良好。但是我怎样才能更换
http://localhost:3000
根据网站的运行位置,有一些“动态”的东西?该站点可以在本地运行 (localhost)、由 Vercel 创建的预览 URL (something-random.now.sh)、另一个 Vercel URL (something-else.now.sh) 或自定义 URL (mydomain.com)。有没有办法确定如何在所有没有 .env
的情况下调用 Next.js/api文件?与 .env
文件我不知道如何为 Vercel 创建的用于预览的“动态”URL(和其他 Vercel URL)设置它。谢谢!
最佳答案
您可以通过设置系统环境变量VERCEL_URL
来获取部署的URL。由 Vercel 填充。
VERCEL_URL
如 姓名 , 留下 值 为空,然后单击 添加 . You can learn more about System Environment Variables in this Vercel Docs.
然后,在
getServerSideProps
里面,您可以通过 process.env.VERCEL_URL
获取 URL .请注意,使用此方法,您可以获得不同环境下的预览网址(something-random.now.sh)和生产网址(something-else.now.sh)。但是当您访问您的自定义域(exmaple.com)时,您仍然会获得生产 URL。
如果您只使用自定义 URL 而不是 Vercel 的生产 URL,则此解决方案可能已经足够好了:
let baseUrl = 'http://localhost:3000'
if(process.env.Vercel_URL) {
baseUrl = process.env.Vercel_URL === 'https://something-else.now.sh'? 'https://exmaple.com': process.env.Vercel_URL
}
如果您需要自定义 URL 和 Vercel 的生产 URL 才能工作,则可能需要其他解决方案。
关于javascript - Next.js getServerSideProps 在本地、PR 预览和生产中使用/api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62337108/