Vite项目中.env导入API Key失效问题及解决方法
Vite项目环境变量读取失败致API Key无效的解决方案
问题情况
在Vite启动的项目中,直接硬编码API Key调用TMDB接口功能正常,但通过.env文件导入时,控制台返回API Key无效错误:
{status_code: 7, status_message: 'Invalid API key: You must be granted a valid key.', success: false}
原代码如下:
const apiKey = import.meta.env.REACT_APP_API_KEY; const getMovies = () => { fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}`) .then((res) => res.json()) .then((json) => console.log(json)) .catch((err) => console.log(err)); }; useEffect(() => { return () => { getMovies(); }; }, []);
问题原因
Vite与Create React App(CRA)的环境变量命名规则存在差异:
- CRA识别
REACT_APP_前缀的环境变量 - Vite仅会暴露以
VITE_开头的变量给客户端代码,原代码中REACT_APP_API_KEY不符合Vite的规则,导致读取不到有效值,接口请求时传递了无效的API Key(通常为undefined)。
解决步骤
- 修改
.env文件中的变量名,将REACT_APP_API_KEY改为VITE_REACT_APP_API_KEY - 调整代码中的变量读取语句:
const apiKey = import.meta.env.VITE_REACT_APP_API_KEY;
- 重启Vite开发服务(环境变量修改后需要重启才能生效)
按上述操作调整后,问题即可解决。
内容的提问来源于stack exchange,提问作者Emir
相关产品推荐
相关产品推荐

