'Network Error while using axios with fastapi (python) running on http://127.0.0.1:8000

I'm trying to integrate an API with my react native app, but when I make the request, I always receive a Network error:

[Unhandled promise rejection: TypeError: Network request failed]
at node_modules\whatwg-fetch\dist\fetch.umd.js:541:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:123:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:379:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

My axios is configured like the following:

import axios from "axios";
const baseUrl = 'http://localhost:8000/' 
export const api = axios.create({baseURL: baseUrl});

Also tried with 'http://10.0.2.2:8000/' and 'http://127.0.0.1:8000', but got the same error.

Could someone help me here? Thank you in advance!!



Solution 1:[1]

By looking at your baseUrl, I guess you are trying to access the local hosted API. So, in order to make it work on an emulator/wired device; you need to do the following steps:

Open commmand prompt, type the following command:

ipconfig

and note down the IPv4 Address. Now, paste that same IPv4 address as the base URL in axios file. E.g.

http://YOUR-IPv4-Address-Here:YOUR-API-PORT

and I hope, this would resolve this 'Network request failed' issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haseeb Ahmed