reactjs - 创建行为异常加载环境变量的 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_URL
或api.defaults.baseURL
,两者都打印为http://localhost:3333
.
另外,如果我写api.post('/students/register', { email, password }, { baseURL: 'http://localhost:3333' });
请求是按预期发出的:POST http://localhost:3333/students/register
,但是如果我通过{ baseURL: baseUrl }
了,AxiosRequestConfig
我得到了原来的问题。
我在问什么
正如你所看到的,我有一个解决方法,但我真的不知道到底发生了什么以及为什么。任何澄清将不胜感激。
解决方案
推荐阅读
- java - 图形 2d 平移和旋转问题
- ruby - 将比较运算符作为参数传递给 Ruby 中的方法
- mongodb - 如何将 db mongo 复制到另一个 mongodb 实例?
- c++ - 三角带上的纹理坐标
- r - RShiny - 从列表中渲染信息框
- android - requestPermissions 不适用于 READ_CALL_LOG 和 WRITE_CALL_LOG 在 android 8.1 API 27
- javascript - 如何将实例变量从 React 组件传递到其 HOC?
- java - 通过 Jackson JSON 将 Java 日期解析为 C#
- c++ - 分段错误,由错误的区间(二维数组)引起
- opengl - 渲染草书字体