Expo React Native项目的Axios配置中未设置环境变量



我正在尝试使用Expo项目根目录中的.env文件,该文件名为axios.ts,其中包含用于Axios请求的API URL。

import axios from 'axios';
const Axios = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
Axios.defaults.headers.common['Content-Type'] = 'application/json';
export default Axios;

为了让它发挥作用,我按照世博会官方文件的建议安装了dot-env

这是我的package.json

{
"main": "index.js",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"start-expo": "expo start",
"test": "jest"
},
"dependencies": {
"@react-native-community/masked-view": "^0.1.10",
"@react-native-community/picker": "1.6.0",
"@react-navigation/drawer": "^5.9.0",
"@react-navigation/material-top-tabs": "^5.2.13",
"@react-navigation/native": "^5.7.0",
"@react-navigation/native-stack": "^5.0.5",
"@react-navigation/stack": "^5.9.0",
"axios": "^0.20.0",
"dotenv": "^8.2.0",
"events": "^3.1.0",
"react": "~16.11.0",
"react-dom": "~16.11.0",
"react-native": "~0.62.2",
"react-native-gesture-handler": "~1.6.0",
"react-native-paper": "^3.10.1",
"react-native-reanimated": "~1.9.0",
"react-native-screens": "~2.9.0",
"react-native-tab-view": "^2.14.4",
"react-native-table-component": "^1.2.1",
"react-native-unimodules": "~0.10.0",
"react-native-vector-icons": "^7.0.0",
"react-native-web": "~0.11.7",
"react-native-webview": "9.4.0",
"react-redux": "^7.2.0",
"redux-saga": "^1.1.3"
},
"devDependencies": {
"@babel/core": "~7.9.0",
"@types/react": "~16.9.23",
"@types/react-dom": "~16.9.8",
"@types/react-native": "~0.61.23",
"@types/react-native-vector-icons": "^6.4.5",
"babel-plugin-inline-dotenv": "^1.6.0",
"babel-preset-expo": "~8.2.0",
"expo": "~38.0.1",
"expo-updates": "~0.2.8",
"jest-expo": "~38.0.0",
"typescript": "~4.0.2"
},
"jest": {
"preset": "react-native"
},
"private": true
}

当然,我还设置了babel.config.js文件

module.exports = function(api) {
api.cache(true);
return {
plugins: ['inline-dotenv'],
presets: ['babel-preset-expo'],
};
};

当我对某个端点进行API调用时,就会出现问题。

import Axios from "../../api/axios";
const login = async () => {
console.log(process.env.REACT_APP_API_URL);
try{
const response = await Axios.post(ENDPOINTS.login,{
email,
password,
device_id
});
console.log(response);
}catch(e){ //TODO : deal with errors
console.log(e);
}
};

当使用.env文件时,请求得到一个404 error,如果我只是直接设置字符串,则请求正常工作。

import axios from 'axios';
const Axios = axios.create({
baseURL: 'http://myurl..." // This is working as expected!
});
Axios.defaults.headers.common['Content-Type'] = 'application/json';
export default Axios;

.env文件似乎没有正确设置,但根据console.log(),它具有正确的值。我怀疑原因是环境变量是在调用Axios函数后设置的,所以一开始它是空的,但当日志出现时,它已经设置好了。

我的解释是否合理,或者是什么其他环境可能导致了这个问题?

第二天测试后,我很惊讶它工作得很好,所以我认为缓存有问题。对于任何面临这个问题的人,我建议删除Expo中的缓存,然后重试

最新更新