You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在public文件夹通过window声明全局变量,src中获取值为undefined的问题咨询

问题解决:全局window.ENV变量获取为undefined的问题

核心原因及解决步骤

1. 修复脚本加载顺序(最可能的原因)

你的问题本质是加载顺序错误:src目录下的代码(包括config.js)在current.js执行前就已运行,此时window.ENV还未被赋值,自然返回undefined。

解决方法:在项目入口HTML文件(通常是public/index.html)中,将current.js的引用放在React打包脚本之前,确保全局变量先被定义:

<!-- 优先加载全局配置脚本 -->
<script src="%PUBLIC_URL%/config/current.js"></script>
<!-- 再加载React打包后的业务脚本 -->
<script src="%PUBLIC_URL%/static/js/main.xxx.js"></script>

(注:如果是Create React App项目,%PUBLIC_URL%会自动映射到public目录路径,无需手动修改)

2. 校验文件路径正确性

确认public/config/current.js的文件位置无误,同时检查HTML中script标签的src路径与实际文件路径完全匹配,避免因路径错误导致脚本未加载。

3. 增加容错兜底(可选)

为避免脚本加载失败等极端情况,可在config.js中增加兜底逻辑:

// src/config/config.js
const defaultEnv = {
    BACK_END_API_URL: 'http://localhost:9998/api'
};

export const {
    BACK_END_API_URL
} = window.ENV || defaultEnv;

修改后完整代码示例

public/config/current.js

window.ENV = {
    BACK_END_API_URL: 'http://localhost:9999/api'
};

src/config/config.js

const defaultEnv = {
    BACK_END_API_URL: 'http://localhost:9998/api'
};

export const {
    BACK_END_API_URL
} = window.ENV || defaultEnv;

src/api/Employee.js

import { BACK_END_API_URL } from '../config/config';
import { apiInstance } from './apiInstance';

const employee_api = apiInstance(`${BACK_END_API_URL}/v1/employees`)

export const getEmployeeByEmail = async (employeeEmail) =>  await employee_api.get(`/employee?email=${employeeEmail}`)

内容的提问来源于stack exchange,提问作者no body

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:14:52