androidreactjslaravelaxioscapacitor

Setup API connection for Reactjs + Laravel API + Capacitor in Android device


There's a problem for API connection. Here I want to make a POST request, but connection failed/network error.

The code:

  1. Home.jsx
try {
      // const response = await axios.post('http://127.0.0.1:8000/api/submitqrcode', { qr_code_data: data },
      //   getConfig()
      // );
      const response = await CapacitorHttp.post({
        url: 'http://127.0.0.1:8000/api/submitqrcode',
        headers: {"Content-Type": "application/json"},
        data: {qr_code_data: data},
      })
  1. capacitor.config.json
{
  "appId": "com.example.app",
  "appName": "QR Code Reader",
  "webDir": "build",
  "plugins": {
    "CapacitorHttp": {
      "enabled": true
    }
  }
}

What I've tried:

  1. using Axios

Error: net::ERR_CONNECTION_REFUSED

  1. using CapacitorHttp

Error: "ConnectException" message: "Failed to connect to /127.0.0.1:8000"

Although I've tried 2 different methods, but both are showing the same type of error, which is can't connect to API. Why and how to solve this?


Solution

  • Ok I have found an insight from people in discord which resulted as a solution in my case.

    So you will need a web server to host your backend. Thanks to my boss's help, here are the steps:

    1. Setup your DB connection and laravel env file with the web server's credentials
    2. Use the web server's url at the axios request in your frontend
    3. Install filezilla (or any that suits you) to save updated files to the server

    Tadaa & you're done!

    So in conclusion, you will need a web server to host your backend in android devices.