Capacitor 6 - Axios Network Error

Capacitor: ^6.1.2
Frontend: React 18
Backend: Ruby on rails
Frontend network requests: Axios (1.11.0)

Hey all, my Capacitor app has started giving me an Axios Network error all of a sudden, which I have added below. It was working perfectly fine on HTTP and HTTPS (hosted) endpoints on a simulator and a physical device, but then it started giving me the Network error. It seems like this happens with GET requests with parameters, because I made a POST request with a request body and that was fine.

I made the same API request, that gave the Network Error, in the simulator browser and the response was correctly displayed.

The backend CORS is setup to handle requests from Capacitor. Nothing was changed in the CORS file too. For the same api call that shows a Network Error on the front end, the backend accepts that request and returns a 200.

The only thing i can think of was a recent update of Axios from ^1.7.5 to ^1.11.0. Reverting to that version does not fix it.

Any help on this would mean a lot!

{
  "message": "Network Error",
  "name": "AxiosError",
  "stack": "handleError@http://192.168.0.248:3000/node_modules/.vite/deps/axios.js:1615:36\n@http://192.168.0.248:3000/node_modules/.vite/deps/axios.js:2143:58",
  "config": {
    "transitional": {
      "silentJSONParsing": true,
      "forcedJSONParsing": true,
      "clarifyTimeoutError": false
    },
    "adapter": [
      "xhr",
      "http",
      "fetch"
    ],
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "env": {},
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    "baseURL": "http://localhost:3001",
    "params": {
      "query": "New",
      "fe_version": "new"
    },
    "signal": {},
    "method": "get",
    "url": "http://localhost:3001/api/v1/endpoint",
    "allowAbsoluteUrls": true
  },
  "code": "ERR_NETWORK"
}
```*emphasized text*

Vite is not a frontend but a build tool. What are you actually using for your frontend?

  • Please share some example code of how you are using Axios
  • Did you enable CapacitorHttp? I recommend not using it unless absolutely necessary.
  • What are your CORS settings in your backend?
  • Where are you getting the error? Android, iOS, Web? If native, have you tried in the web browser?
  • Have you looked in DevTools to see if there are any other errors?

Yes, you’re correct, sorry for the oversight on my part. I am using React 18.

  • “Please share some example code of how you are using Axios”

Here is a snippet of my Axios service GET function.

const axiosClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
});

export function getRequest({
  url,
  params = {},
  signal,
  options = {},
}: GetRequestParams): Promise<AxiosResponse> {
  const headers = mergeHeaders(
    (options.headers as Record<string, string>) || {},
    {},
  );

  return axiosClient
    .get(url, {
      params,
      headers,
      signal,
      ...options,
    })
    .then((res) => res)
    .catch((error) => throw error);
}

This is how I use the getRequest function.

    const response = await getRequest({
      url: `${import.meta.env.VITE_API_URL}/api/v1/endpoint`,
      params: { query },
      signal,
    });
  • “Did you enable CapacitorHttp? I recommend not using it unless absolutely necessary.”

Yes, I have it enabled in my capacitor config file. If i remember correctly, I enabled it because, initially the API requests were giving an issue being accepted by the backend. Update: It was a CORS issue all along.

  "plugins": {
    "CapacitorHttp": {
      "enabled": true
    }
  },
  • “What are your CORS settings in your backend?”

For development it is as follows:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  if Rails.env.development?
    allow do
      origins [
        'https://localhost',
        'http://localhost',
        'capacitor://localhost',
        'http://localhost:3000',
        'http://localhost:7173',
        'http://localhost:6173',
        'http://localhost:5173',
        'http://localhost:4173',
        'http://localhost:4000',
        %r{^http://192\.168\.\d{1,3}\.\d{1,3}:4173$},
        %r{^http://192\.168\.\d{1,3}\.\d{1,3}:5173$},
        %r{^http://192\.168\.\d{1,3}\.\d{1,3}:6173$},
      ]
      resource '*',
        headers: :any,
        methods: %i[get post put patch delete options head],
        expose: ['Content-Disposition']
    end
  end
  • “Where are you getting the error? Android, iOS, Web? If native, have you tried in the web browser?”

I am getting this error on the iOS simulator and physical device. I have not run it on Android yet. The same APIs are running perfectly fine on web, in dev and production.

  • “Have you looked in DevTools to see if there are any other errors?”

This is what I got in the dev tools console after I removed the CapacitorHttp. For some reason, when I enable it, it does not connect to the dev tools. The cross origin error is exactly why i added the enabled CapacitorHttp. I guess I should focus on fixing this issue by disabling CapacitorHttp, as you mentioned it’s not recommended. Any help on how to fix the error below?

[Error] Origin http://192.168.0.248:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200

[Error] Failed to load resource: Origin http://192.168.0.248:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200 (capacitor_http_interceptor, line 0)

[Error] XMLHttpRequest cannot load capacitor://localhost/capacitor_http_interceptor?u=http%3A%2F%2Flocalhost%3A3001%2Fapi%2Fv1%2Fproperties%2Fautocomplete%3Fquery%3DNew%26fe_version%3Dnew due to access control checks.

Thanks for the details!!!

Having CapacitorHttp enabled intercepts all requests and sends them through native land so that is why you wouldn’t see it in DevTools. It should only be used if you don’t control the server you are trying to connect to and you cannot configure CORS. It was primarily created to support 3rd Party services that do not allow a localhost or capacitor origin. Running requests through native land completely removes CORS as it doesn’t exist there. But, it does add some overhead as every request/response has to be serialized/deserialized between native land and the web layer. Hence, not recommended if you don’t absolutely need it.

In regards to this new error, I don’t see http://192.168.0.248:3000 in your Ruby CORS config.

Thank you for explaining CapacitorHttp! I’ll remove that since we use our own server.

I added %r{^http://192\.168\.\d{1,3}\.\d{1,3}:3000$} to the origins array and it worked :tada:
I can’t believe it was such a simple oversight..

One more thing I wanted to confirm, you mentioned in another post that we have to add the following to the production, and staging in our case, CORS origins array for it to work.

  • iOS: capacitor://localhost
  • Android: http://localhost

I made a release build on an iOS simulator and indeed got capacitor://localhost in window.location.origin. Is it still the case? Is there any way for us to change or specify the origin when making a release build? Also, I didn’t find this origin specification in the docs, it would be great if this could be mentioned there in the setup section.

1 Like

As an FYI, I believe starting in Capacitor 6, Android defaults to https now so https://localhost. I still have both (http and https) on our server.

For iOS, capacitor://localhost is still the case. It is documented in the Config docs under server.iosScheme.

There is this note:

Can’t be set to schemes that the WKWebView already handles, such as http or https

Great, thanks again! @twestrick

1 Like