Javascript Next.js getServerSideProps在本地、PR预览和生产中使用/api
这几乎直接来自Next.js站点上的一些示例Javascript Next.js getServerSideProps在本地、PR预览和生产中使用/api,javascript,reactjs,next.js,Javascript,Reactjs,Next.js,这几乎直接来自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
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;
功能主页(道具){
返回(
欢迎来到{props.data.name}Next.js
);
}
//每次请求都会调用此函数
导出异步函数getServerSideProps(上下文){
const res=等待取数('http://localhost:3000/api/test');
const data=wait res.json();
//通过道具将数据传递到页面
返回{props:{data}};
}
导出默认主页;
当然,该代码在本地非常有效。但是如何替换http://localhost:3000
是否根据站点运行的位置提供“动态”功能?该站点可以在本地运行(localhost)、由Vercel创建的预览URL(random.now.sh)、另一个Vercel URL(other.now.sh)或自定义URL(mydomain.com)。有没有办法确定如何在所有没有.env
文件的系统上调用Next.js/api?使用.env
文件,我不知道如何为Vercel为预览创建的“动态”URL(以及其他Vercel URL)设置它
谢谢 您可以通过设置由VERCEL填充的系统环境变量
VERCEL\u URL
来获取部署的URL
VERCEL\u URL
作为名称,将值保持为空,然后单击添加getServerSideProps
中,您可以使用process.env.VERCEL\u URL
获取URL
请注意,使用此方法,您可以在不同的环境下获得预览URL(random.now.sh)和生产URL(other.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,您可能需要另一个解决方案。为什么不使用
next.config.js
文件?谢谢@Hangindev,我缺少Vercel\u URL
环境变量。