The "Exception: Network Error" you're encountering in your React Native application typically indicates that Axios is unable to establish a connection to your API server. This can be due to several reasons, ranging from incorrect Axios configuration to issues with network permissions on the device. Below are detailed steps to help you diagnose and resolve this issue.
1. Verify Axios Configuration
a. Ensure Correct Base URL and Endpoints
First, confirm that your Axios instance is correctly configured with the right base URL and that the endpoints used in your service layer match those defined on your server.
Example Configuration:
// axiosConfig.ts
import axios from 'axios';
const apiServer = axios.create({
baseURL: 'https://your-api-base-url.com', // Replace with your actual base URL
timeout: 10000, // Optional: Set a timeout for requests
headers: {
'Content-Type': 'application/json',
// Add other headers if necessary, such as Authorization tokens
},
});
export default apiServer;
b. Instantiate Your Service Correctly
Ensure that your AlthermaService is instantiated with the configured Axios instance.
Example:
// altherma.ts
import apiServer from './axiosConfig'; // Adjust the path as needed
import AlthermaService from './AlthermaService'; // Adjust the path as needed
export const althermaService = AlthermaService(apiServer);
Ensure Correct Import in Your Screen:
import { althermaService } from "@services/api/altherma"; // Adjust the path as needed
2. Handle Axios Errors More Effectively
Enhance your error handling to get more detailed information about the network error. This can help pinpoint the exact issue.
Updated Error Handling in Your Screen:
const runScanApi = async () => {
showLoader(true);
try {
const result = await althermaService.scanWifiNetworks();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
if (error.isAxiosError) {
if (error.response) {
// Server responded with a status other than 2xx
setApiResponse(`Error: ${JSON.stringify(error.response.data)}`);
} else if (error.request) {
// Request was made but no response received
setApiResponse(`No response received: ${error.message}`);
} else {
// Something happened setting up the request
setApiResponse(`Request setup error: ${error.message}`);
}
} else {
// Non-Axios error
setApiResponse(`Unexpected error: ${error.message}`);
}
} finally {
showLoader(false);
}
};
Repeat Similar Enhancements for Other API Handlers (runNetworksApi, runSettingsApi, runInfoApi).
3. Check Network Permissions
a. Android
Ensure that your AndroidManifest.xml includes the Internet permission. Without this, your app won't be able to make network requests.
<!-- AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
b. iOS
If you're using non-HTTPS endpoints, you need to adjust the App Transport Security (ATS) settings in your Info.plist. However, it's recommended to use HTTPS to avoid these issues.
<!-- Info.plist -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Note: Allowing arbitrary loads is not recommended for production apps. Instead, ensure that your API endpoints use HTTPS.
4. Verify API Server Accessibility
a. Test API Endpoints
Use tools like Postman or cURL to test your API endpoints independently of your app. This helps ensure that the server is up and the endpoints are functioning correctly.
curl -X POST https://your-api-base-url.com/wifi/ap/scan
b. Check SSL Certificates
If your API uses HTTPS, ensure that the SSL certificates are valid. Self-signed certificates can cause Axios to reject requests unless explicitly configured to accept them (which is generally not recommended for production).
5. Ensure Device Connectivity
a. Emulator Configuration
If you're testing on an emulator:
-
Android Emulator: Ensure that the emulator has network access. Check other apps or browsers within the emulator to verify connectivity.
-
iOS Simulator: Similar to Android, ensure that the simulator can access the internet.
b. Physical Device
If testing on a physical device:
- Ensure that the device is connected to the internet.
- Verify that there are no VPNs or firewalls blocking the connection.
6. Review Network Logs
a. Enable Axios Logging
You can add interceptors to Axios to log requests and responses, which can be invaluable for debugging.
// axiosConfig.ts
apiServer.interceptors.request.use(
(config) => {
console.log('Starting Request', config);
return config;
},
(error) => {
console.error('Request Error', error);
return Promise.reject(error);
}
);
apiServer.interceptors.response.use(
(response) => {
console.log('Response:', response);
return response;
},
(error) => {
console.error('Response Error:', error);
return Promise.reject(error);
}
);
b. React Native Debugger
Use tools like React Native Debugger or Flipper to inspect network requests made by your app.
7. Sample Correct Implementation
Here's how you can bring it all together with a sample implementation:
a. Axios Configuration (axiosConfig.ts):
import axios from 'axios';
const apiServer = axios.create({
baseURL: 'https://your-api-base-url.com', // Replace with your actual base URL
timeout: 10000, // Optional timeout
headers: {
'Content-Type': 'application/json',
// Add other headers here
},
});
// Optional: Add interceptors for logging
apiServer.interceptors.request.use(
(config) => {
console.log('Starting Request', config);
return config;
},
(error) => {
console.error('Request Error', error);
return Promise.reject(error);
}
);
apiServer.interceptors.response.use(
(response) => {
console.log('Response:', response);
return response;
},
(error) => {
console.error('Response Error:', error);
return Promise.reject(error);
}
);
export default apiServer;
b. Service Layer (altherma.ts):
import apiServer from './axiosConfig'; // Adjust the path as needed
import AlthermaService from './AlthermaService'; // Adjust the path as needed
export const althermaService = AlthermaService(apiServer);
c. Service Implementation (AlthermaService.ts):
(Assuming this is the same as the code you provided. Ensure it's correctly importing types and constants.)
import { AxiosError, AxiosInstance, AxiosResponse } from "axios";
// ... other imports
type ApiResult<T> = iNetworkResult<T> | iNetworkError;
const AlthermaService = (apiServer: AxiosInstance) => {
const handleApiRequest = async <T>(
requestFn: () => Promise<AxiosResponse<T>>,
): Promise<ApiResult<T>> => {
try {
const response = await requestFn();
return {
error: null,
status: response.status,
data: response.data,
} as iNetworkResult<T>;
} catch (error) {
const axiosError = error as AxiosError;
if (axiosError.response) {
const { status, data } = axiosError.response;
return {
error: data,
status,
data,
} as iNetworkError;
}
// Throw again if the error is not an Axios error with a response
throw error;
}
};
const scanWifiNetworks = () => {
return handleApiRequest(() => {
return apiServer.post(apiEndpoints.wifi.ap.scan);
});
};
const getAvailableNetworks = () => {
return handleApiRequest<iWLANScanResponse>(() => {
return apiServer.get(apiEndpoints.wifi.ap.networks);
});
};
const configureWifiConnection = (settings: iWLANSettings) => {
return handleApiRequest(() => {
return apiServer.put(apiEndpoints.wifi.ap.settings, settings);
});
};
const getWlanInfo = () => {
return handleApiRequest<iWLANInfo>(() => {
return apiServer.get(apiEndpoints.wifi.ap.info);
});
};
return {
scanWifiNetworks,
getAvailableNetworks,
configureWifiConnection,
getWlanInfo,
};
};
export default AlthermaService;
d. Screen Implementation (AlthermaAPIsTestScreen.tsx):
(Ensure you correctly import althermaService and handle errors as shown earlier.)
import React, { useContext, useEffect, useState } from "react";
import { ScrollView, Text, View } from "react-native";
import { useNavigationState } from "@react-navigation/native";
import { StackScreenProps } from "@react-navigation/stack";
import Alert from "@components/alert";
import Background from "@components/background";
import Icon from "@components/icon";
import Label from "@components/label";
import Button from "@components/primaryButton";
import { DEFAULT_INITIAL_ALERT_STATUS } from "@config/constants/AppConstants";
import { HomeNavigatorParamList } from "@config/constants/NavConstants";
import { ALTHERMA_SSID } from "@config/constants/ThermostatConstants";
import { MINI_SPLIT_CONNECT_TIMEOUT } from "@config/constants/TimeoutConstants";
import { translationKeys } from "@config/constants/TranslationConstants";
import Images from "@config/Images";
import { getLocalizationContext } from "@config/Translations";
import { iAlertState } from "@config/types/CommonTypes";
import { althermaService } from "@services/api/altherma";
import { useAppDispatch } from "@store/Hooks";
import {
hideLoader as hideFanLoader,
showLoader as showFanLoader,
} from "@store/loader/LoaderSlice";
import { useThemeAwareObject } from "@styles/theming/ThemingHelper";
import { isConnectedToSSIDPrefix, timeout } from "@utils/WifiManagerUtils";
import { iWLANSettings } from "config/types/AppDataTypes/AlthermaTypes";
import Styles from "./Styles";
type Props = StackScreenProps<HomeNavigatorParamList, "AlthermaAPIsTestScreen">;
const AlthermaAPIsTestScreen = ({ navigation }: Props) => {
const { translate } = useContext(getLocalizationContext());
const styles = useThemeAwareObject(Styles.createStyles);
const dispatch = useAppDispatch();
const routes = useNavigationState((state) => state.routes);
const [alertStatus, setAlertStatus] = useState<iAlertState>(
DEFAULT_INITIAL_ALERT_STATUS,
);
const [apiResponse, setApiResponse] = useState<string>("");
const closeButton = () => {
return (
<Icon
Image={Images.svgIcons.crossButton}
color={styles.crossIcon.color}
onPress={async () => {
await reboot();
}}
/>
);
};
useEffect(() => {
navigation.setOptions({
headerLeft: (): JSX.Element => closeButton(),
});
}, []);
const showLoaderHandler = (loading: boolean) => {
if (loading) {
dispatch(showFanLoader());
} else {
dispatch(hideFanLoader({ className: "AlthermaAPIsTestScreen" }));
}
};
// Enhanced error handling function
const handleApiError = (error: any) => {
if (axios.isAxiosError(error)) {
if (error.response) {
return `Error: ${JSON.stringify(error.response.data)}`;
} else if (error.request) {
return `No response received: ${error.message}`;
} else {
return `Request setup error: ${error.message}`;
}
} else {
return `Unexpected error: ${error.message}`;
}
};
// Handler for Scan API
const runScanApi = async () => {
showLoaderHandler(true);
try {
const result = await althermaService.scanWifiNetworks();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(handleApiError(error));
} finally {
showLoaderHandler(false);
}
};
// Handler for Networks API
const runNetworksApi = async () => {
showLoaderHandler(true);
try {
const result = await althermaService.getAvailableNetworks();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(handleApiError(error));
} finally {
showLoaderHandler(false);
}
};
// Handler for Settings API
const runSettingsApi = async () => {
showLoaderHandler(true);
try {
const settings: iWLANSettings = {
ssid: "Hathway_Ashish2.4G",
security: "WPA_WPA2_MIXED",
key: "8296494290",
};
const result = await althermaService.configureWifiConnection(settings);
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(handleApiError(error));
} finally {
showLoaderHandler(false);
}
};
// Handler for Info API
const runInfoApi = async () => {
showLoaderHandler(true);
try {
const result = await althermaService.getWlanInfo();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(handleApiError(error));
} finally {
showLoaderHandler(false);
}
};
const navigateBack = () => {
showLoaderHandler(false);
const filteredRoutes = routes.filter((item) => item.name === "ConfigureThermostatScreen");
if (filteredRoutes.length > 0) {
navigation.pop(1);
}
navigation.goBack();
};
const reboot = async () => {
showLoaderHandler(true);
const isConnectedToMiniSplitSSID = await isConnectedToSSIDPrefix(ALTHERMA_SSID);
if (isConnectedToMiniSplitSSID.isConnected) {
// await rebootAdapter();
await timeout(MINI_SPLIT_CONNECT_TIMEOUT);
navigateBack();
} else {
navigateBack();
}
};
const onDismissAlert = () => {
setAlertStatus({
...alertStatus,
isVisible: false,
onPress: null,
onCancel: null,
});
};
return (
<Background style={styles.root}>
<View style={styles.container}>
<Alert
visible={alertStatus.isVisible}
title={alertStatus.title}
buttonAlignment={alertStatus.buttonAlignment}
description={alertStatus.message}
positiveButtonTitle={
alertStatus.positiveBtnLabel ||
translate(translationKeys.alert.okayButtonLabel)
}
negativeButtonTitle={alertStatus.negativeBtnLabel}
alternateButtonTitle={alertStatus.alternativeBtnLabel}
onPress={alertStatus.onPress || onDismissAlert}
onCancel={alertStatus.onCancel || onDismissAlert}
onPressAlternate={alertStatus.onPressAlternate || onDismissAlert}
/>
<Label
text="Click on the buttons below to check the Altherma APIs"
style={styles.description}
/>
<Button
title="Run Scan API"
style={[styles.scanButton]}
onPress={runScanApi}
/>
<Button
title="Run Networks API"
style={[styles.scanButton]}
onPress={runNetworksApi}
/>
<Button
title="Run Settings API"
style={[styles.scanButton]}
onPress={runSettingsApi}
/>
<Button
title="Run Info API"
style={[styles.scanButton]}
onPress={runInfoApi}
/>
<View style={styles.responseWrapper}>
<ScrollView
style={styles.responseContainer}
contentContainerStyle={{ flexGrow: 1 }}
>
<Text style={styles.responseText}>
{apiResponse ||
"API response will appear herecjc \n cj cjlc c cj cjac cl scdhc hk."}
</Text>
</ScrollView>
</View>
</View>
</Background>
);
};
export default AlthermaAPIsTestScreen;
8. Additional Tips
-
Use HTTPS: Ensure that your API endpoints use HTTPS to avoid issues related to insecure connections.
-
Avoid Hardcoding Sensitive Data: Instead of hardcoding SSIDs and keys, consider using environment variables or secure storage solutions.
-
Clean and Rebuild: Sometimes, after making changes to configurations or permissions, it's helpful to clean your build and reinstall the app.
# For Android
cd android && ./gradlew clean && cd ..
# For iOS
cd ios && xcodebuild clean && cd ..
# Reinstall dependencies and rebuild
npm install
npx react-native run-android
# or
npx react-native run-ios
-
Check for Emulator/Device Logs: Use adb logcat for Android or Xcode's console for iOS to view detailed logs that can help diagnose network issues.
9. Summary
The "Network Error" is often a result of misconfigured Axios instances, missing network permissions, incorrect API endpoints, or issues with network connectivity. By following the steps outlined above, you should be able to identify and rectify the underlying cause of the error. Here's a quick checklist:
- Verify Axios Base URL and Endpoints
- Enhance Error Handling for Detailed Insights
- Ensure Network Permissions are Set
- Confirm API Server Accessibility
- Ensure Device or Emulator Connectivity
- Inspect Network Logs for Clues
Implement these steps systematically, and you should be able to resolve the network error in your React Native application.