Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Next.js getServerSideProps在本地、PR预览和生产中使用/api_Javascript_Reactjs_Next.js - Fatal编程技术网

Javascript Next.js getServerSideProps在本地、PR预览和生产中使用/api

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

这几乎直接来自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;
功能主页(道具){
返回(
欢迎来到{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中的项目设置页面
  • 在“环境变量”部分,输入
    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
    环境变量。