简体   繁体   中英

Vuejs get request from PHP/MySQL doesn't work

I am writing code to get data from MySQL database and using Vuejs,

this.$http.get("api.php?action=read")
        .then(response => {
          console.log(response);
        }, error => {
          console.log(error);
        });

this request returns all api.php content and doesn't return the data.

here is the api.php file

<?php

  require_once('include/config.php');

  $res = (['error' => false]);

  $action = 'read';

  if (isset($_GET['action'])) {
    $action = $_GET['action'];
  }

  if($action == 'read') {
      $images = array();

      $query = 'SELECT * FROM images ORDER BY id DESC';
      $select_images = mysqli_query($connection, $query);
      while($image = mysqli_fetch_assoc($select_images)) {
        array_push($images, $image);
      }
      echo json_encode($images);
  }

  mysqli_close($connection);
  header("Content-type: application/json");
  echo json_encode($images);
  die();
?>

Can anyone help me, Please?

It works,

I added

header("Access-Control-Allow-Origin: *");

to the API file

and make the get request from the localhost/vuejs link, not like localhost:8080 and it's work

Thanks

Include the header in the php. Note: should be the 1st line before you return anything.

<?php
header("Access-Control-Allow-Origin: *");

And try to run the php code 1st using command prompt:

php -S localhost:8888 ajaxfile.php

Note: try to use different port number as for me it is unable to get the api from same 8080 port in which my vueProject is running. This will create an api end point with your php. Which will listen to http://localhost:8888/projectname/api.php .

Now When used axios.get( http://localhost:8888/projectname/api.php ) will get the response for the api.I havent tried without axios module but i guess it should work.

allRecords: function(){
  axios.get('http://localhost:8888/VueAxios/ajaxfile.php').then(response => {
    this.users = response.data
    console.log(response.data)
  })
  .catch(function (error) {
    console.log(error);
  });
}

This function worked for me. Note: axios is a very handy in this situation. Hope it helps.

Try response.body to get the response data:

this.$http.get("api.php?action=read")
        .then(response => {
          console.log(response.body);
        }, error => {
          console.log(error);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM