【问题标题】:Problem with reading URL environment variable with .env file in React and Typescript在 React 和 Typescript 中使用 .env 文件读取 URL 环境变量的问题
【发布时间】:2022-01-17 03:16:57
【问题描述】:

我是 react-typescript 的新手,我在 src 文件夹中创建了名为 process.env 的 .env 文件。我将我的网址设为REACT_APP_API_ENDPOINT=http://localhost:8080/prices

在我的 App.tsx 中,我使用如下:

const { REACT_APP_API_ENDPOINT } = process.env;
const search = async (): Promise<any> => {
  const res = await fetch(`${REACT_APP_API_ENDPOINT}`);
  return (await res.json()).results;
};
useEffect(() => {
  (async () => {
    const prices = await search();
    setPrice(prices);
  })();
}, []);

package.json:

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}

问题是没有从给定的 url 获取数据,我在这里做错了什么?是因为我在 src 文件夹中创建了 process.env,还是因为我在 VS 代码中安装了 DotENV(mikestead) 扩展..

【问题讨论】:

    标签: reactjs typescript url environment-variables fetch


    【解决方案1】:

    dot-env 包的默认路径是 root 文件夹,但如果你想设置自定义路径,你可以使用下面的代码来做到这一点。

    require('dotenv').config({ path: '/custom/path/to/.env' })
    

    您可以参考https://www.npmjs.com/package/dotenv了解更多信息。

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 2021-01-18
      • 2015-12-10
      • 2021-03-12
      • 1970-01-01
      • 2020-02-13
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多