Access the result of AXIOS JS

0

Good afternoon, I am making use of the Javascript AXIOS library for calls to the server and consumption of an API. Everything works fine, but I need to know how the elements of the JSON result can be put into variables to access them.

For example, with HTTPRequest this code was used:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", $urlEnvio, false);
xmlhttp.setRequestHeader("accept" ,"application/json");
xmlhttp.setRequestHeader("content-type" ,"application/json");
xmlhttp.send($urlEnvio);

var resultado = xmlhttp.response;
var elementos =JSON.parse(resultado);

This made me request the API and then I inserted the results in the variable elements, being able to access one of them by entering elements [0] or the position that was.

On the other hand, with AXIOS the fragment works correctly, but the part of JSON.parse used with HTTPRequest I can not apply it. Here is the fragment of my application with AXIOS:

axios.get(urlEnvio, usuario, clave)
.then(response => {
  // JSON responses are automatically parsed.
  this.posts = response.data
  //var elementos = JSON.stringify(posts);
  alert(posts[0]);

})

In the alert I get the UNDEFINED message. I appreciate any help, thank you very much.

    
asked by AntonioMP87 30.05.2017 в 13:57
source

1 answer

1

As it says there, the answers in json format are automatically parsed (you have to return json in the shipping url), then

var elementos = [];
axios.get(urlEnvio, usuario, clave)
.then(response => {
  // JSON responses are automatically parsed.
  elementos = response.data;
});

BUT be careful what you send to the get. Get accepts a second parameter which are the request config, one of the config options is param, so you should do

var elementos = [];
axios.get(urlEnvio, , {
 params: {
   user: usuario,
   pass: clave
 }
})
.then(response => {
  // JSON responses are automatically parsed.
  elementos = response.data;
});

and an example of /login.php (of course, not sure)

$response = [];
$response['logged'] = false;
if($_GET['user']=="oxxido" && $_GET['pass']=="superseguro") {
  $response['logged'] = true;
}
echo json_encode($response);

More info:

here you have examples of get and save using an api:

// GET request
axios.get('https://api.github.com/users/oxxido')
  .then(function(response){
    console.log(response.data); // ex.: { user: 'Your User'}
    console.log(response.status); // ex.: 200
  });  

// guardando POST request
axios.post('/save', { firstName: 'Oxxido', lastName: 'Test' })
  .then(function(response){
    console.log('Guardado exitoso')
  });

Note two things, "this" within axios.get refers to the axios object, so use this carefully. Axios.get returns a promise, so its execution is asynchronous.

Greetings!

    
answered by 30.05.2017 / 14:35
source