Can I use Vue-native with mysql

468 views Asked by At

Hello everyone I'm trying to develop an android app.

I tried to connect the app to the remote mysql server with php using axios (it works when i run the code with vuejs on web.)

here is the Vue-native code;

      fetchAllData:function(){
      axios.post('db.php', {
      action:'fetchall'
      }).then(function(response){
      app.allData = response.data;
      });

here is the db.php file:

$received_data = json_decode(file_get_contents("php://input"));
$data = array();
if($received_data->action == 'fetchall')
{
 $query = "
 SELECT * FROM users ";
 $statement = $connect->prepare($query);
 $statement->execute();
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

and here is the error:

Error's screenshoot

1

There are 1 answers

5
onestepp On

The error you have is a network error, saying either you dont have internet connection or the endpoint is unreachable.

Are you trying to connect to a valid endpoint?

You can set up your endpoint in axios like that:

export const apiParams = {
  baseURL: 'YOUR URL HERE',
  timeout: 20000,
  withCredentials: true
}
const api = axios.create(apiParams)

After exporting you can easily use

api.post('db.php', { data });

Basically the unhandled promise rejection is about to saying that axios.post is a promise, and if it is rejected you should handle its error.

Try to put axios.post in a try catch block and you can use ES6 async/await like that:

methods: {
      async fetchAllData() {
        try {
          await axios.post('db.php', {
            action: 'fetchall'
          })
          app.allData = response.data
        } catch (error) {
          console.log(error)
        }
      }
    },

or you can use the old fashion way error handling with catch, but I don't recommend to use it, if you have a chain of promises, is better to use async/await as the example above.

methods: {
      fetchAllData() {
        axios
          .post('db.php', {
            action: 'fetchall'
          })
          .then(function(response) {
            app.allData = response.data
          })
          .catch(err => {
            console.log(err)
          })
      }
    },

Read about promise handling with then/catch https://javascript.info/promise-error-handling Async await: https://javascript.info/async-await

Until you resolve the network error, the promise rejection should be gone, but you will have a handled error on your console log.