首页 > 解决方案 > 创建行为异常加载环境变量的 React App

问题描述

发生了什么

这是一个 TypeScript Node.js/React 项目。我正在axios@^0.21.1用作我的 HTTP 客户端,并且我的应用程序正在向格式错误的 URL ( http://localhost:3000/ĥttp://localhost:3333/path-to-resource) 发送请求以进行任何 api 调用。我预计会向http://localhost:3333/path-to-resource.

这个 URL 是从我的项目根文件夹中的 .env 文件加载的,我相信这是Create React App加载 .env 变量的问题,因为如果我运行应用程序REACT_APP_API_URL='http://localhost:3333' react-scripts start而不是REACT_APP_API_URL从 .env 文件加载,一切正常美好的。此外,这个问题不会发生在暂存环境(部署在 Netlify)上。

到目前为止,我已经做了什么来诊断这个

我将 React 开发服务器托管在localhost:3000,我的 Node.js 服务器托管在localhost:3333. 通过使用 构建应用程序react-scripts build并使用serve -s build -l 4000.

以下是 api 调用的一个示例:

// RegisterPage/index.tsx

const RegisterPage: React.FC = () => {
  // ...
  const handleRegister = useCallback(
    (email, password) => {
      api
        .post(`/students/register`, {
          email,
          password,
        })
        .then(() => {
          signIn({ email, password });
        })
        .catch(error => {
          // ...error handling
        });
    },
    [signIn],
  );

  return (
    {/* ... */}
    <CredentialsForm
      submitButtonLabel="register"
      onSubmit={handleRegister}
    />
    {/* ... */}
  );
};

我从以下位置导入api

// services/api.ts

const config: AxiosRequestConfig = {
  baseURL: apiUrl,
};

const api = axios.create(config);

export default api;

apiUrl从配置文件中:

// config/api.ts

// REACT_APP_API_URL is being loaded from a .env file
export const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:3333';

如果我根本不配置 axios(通过调用axios.create()without config)请求http://localhost:3000(正如预期的那样,因为那是我托管 React 开发服务器的地方)。这里让我感到困惑的是,如果我登录process.env.REACT_APP_API_URLapi.defaults.baseURL,两者都打印为http://localhost:3333.

另外,如果我写api.post('/students/register', { email, password }, { baseURL: 'http://localhost:3333' });请求是按预期发出的:POST http://localhost:3333/students/register,但是如果我通过{ baseURL: baseUrl }了,AxiosRequestConfig我得到了原来的问题。

我在问什么

正如你所看到的,我有一个解决方法,但我真的不知道到底发生了什么以及为什么。任何澄清将不胜感激。

标签: reactjstypescriptaxioscreate-react-app

解决方案


推荐阅读