I need help to configure Axios client according to Wi-FI/3G/4G network

Asked

Viewed 388 times

-2

I’m developing an app in React-Native using expo, and the app works well on the Wi-Fi from here, but it should also work outside of here, and we have a firewall port that points to API nodejs by our public ip. I don’t know if I was clear but basically:

In Enterprise Wi-Fi, Axios must have attr baseUrl= 10.X.X.X And out of Wi-Fi or with Wi-Fi from another location the baseUrl= 189.X.X.X attr

Yes the app needs to stay here, I thought for also a Hostgator or Godaddy of life but will not roll no.

I was able to get the connection with Comunity/Netinfo, but when I use Axios it exports const before setting the IP:

import axios from 'axios'
import NetInfo from "@react-native-community/netinfo"

var ip

NetInfo.addEventListener(state => {
    ip = state.type != 'wifi' ? 'http://189.X.X.X:3333' : state.details.ssid == 'WIFI_EMPRESA' ? 'http://10.X.X.X:3333' : 'http://189.X.X.X:3333'
})

const api = axios.create({
    baseURL: ip,
})

console.log(ip)


export default api

The result of this when opening the app is Undefined, but if I save and update it shows the IP, but at the first moment of 'Network Error'

Someone could fix it, or give me a different solution to it.

Att.

1 answer

0

You can try to define your Axios instance before adding the Event Listener, without passing a baseURL to it, and the Event function Listener set the baseURL of your Axios instance.

import axios from 'axios'
import NetInfo from "@react-native-community/netinfo"

var ip

const api = axios.create({})

NetInfo.addEventListener(state => {
    ip = state.type != 'wifi' ? 'http://189.X.X.X:3333' : state.details.ssid == 'WIFI_EMPRESA' ? 'http://10.X.X.X:3333' : 'http://189.X.X.X:3333'
    api.defaults.baseURL = ip
})

console.log(ip)

export default api
  • I tried this you suggested but the error continues: Finished building Javascript Bundle in 6160ms. Undefined Running application on moto g(7) plus. 

[Unhandled promise rejection: Error: Network Error]
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/adapters/xhr.js:80:22 in handleError

  • I looked it up here and maybe the answer to that problem is here: https://stackoverflow.com/questions/49798540/how-to-export-a-variable-that-takes-its-value-from-an-async-function basically, vc have to ensure that the function that defines the ip is executed before the first call to the api made with Axios, maybe vc can export this function as well and run it before the call to api, with a await

  • I tried to follow the example, but it also did not work, the error remains the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.