Vertix
Vertix

Reputation: 16

I cant display data from laravel api

I am trying to get data from my laravel app, and display it in Vue CLI. I see the Response, but I can not display it in the VUE application.

enter image description here When i do get to example API it's works, but not from my laravel server.

<template>
  <div id="app">
     <h1>{{ results }}</h1>
  </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
      return{
         results: null
      }
    },

    mounted() {
        axios.get('http://127.0.0.1:8000/api/')
            .then(response => {
                this.results = response.data.results
            })
    }
}
</script>

Upvotes: 0

Views: 806

Answers (2)

Vertix
Vertix

Reputation: 16

The answer was Cross-Origin Resource Sharing.

To connect laravel API with front-end i need to do add barryvdh/laravel-cors by composer.

composer require barryvdh/laravel-cors

Next add middleware in app/Http/Kernel.php to enable using API outside laravel APP. In my problem to Vue Cli.

Upvotes: 0

matticustard
matticustard

Reputation: 5149

Your results are being received as an array of objects, a JSON encoded Laravel collection. You need to single out the object you want to display, and then a property of that object.

<div id="app">
    <h1>{{ results[0].name }}</h1>
</div>

However, you should really only be returning one object if this is the case from your controller method, not an array of objects. (e.g., ->first() instead of ->get())

<div id="app">
    <h1>{{ result.name }}</h1>
</div>

Collections are generally for displaying multiple results in lists, table, options, etc.:

<div id="app">
    <ul>
        <!-- v-for will loop through results -->
        <li v-for="(result, index) in results">{{ result.name }}</li>
    </ul>
</div>

EDIT:

Also, your results declaration needs to be adjusted according to the Network response.

this.results = response.data.results;

Should be:

this.results = response.data;

Or alternatively, your controller response needs to be:

return response()->json(['results' => $results]);

Upvotes: 1

Related Questions