0

I just started to learn Vue 3 with Laravel, and I created an app where I have this:

Post Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'content'
    ];
}

In PostsController, I have this function where I want to get all posts:

 public function index()
    {
        $posts = Post::all();
        return response()->json([
            'posts' => $posts,
        ], 200);
    }

In routes/api.php:

Route::get('/posts', [PostsController::class, 'index']);

And this is my Vue Component:

<template>
    <div>
        <ul>
            <li v-for="post in posts" :key="post">
                {{post.title}}
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data(){
        return{
            posts: []
        }
    },
    created(){
      fetch('http://vue-laravel.test/api/posts')
        .then(response => {
            console.log(response)
        })
       
    },
    methods:{
       
    }
}
</script>

This is the sample data:

{
    "success": true,
    "message": "List of all Posts",
    "data": [
        {
            "id": 2,
            "title": "Second",
            "content": "Second post",
            "created_at": "2021-01-27T08:08:21.000000Z",
            "updated_at": "2021-01-27T08:08:21.000000Z"
        },
        {
            "id": 1,
            "title": "First",
            "content": "This is my first post",
            "created_at": null,
            "updated_at": null
        }
    ]
}

BUT when I console.log this fetch, I get this:

screenshot

With console.log(response.data), I get undefined. Any suggestions?

1 Answer 1

2

The resolved result of fetch() (a Body object) should be converted to JSON with Body.json():

fetch('http://vue-laravel.test/api/posts')
  .then(resp => resp.json())
  .then(json => this.posts = json.data)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes i get it with json.posts.. 5 minutes before that i tried with : async getPosts(){ const response = await fetch('vue-laravel.test/api/posts') const responseData = await response.json() console.log(responseData.posts) this.posts = responseData.posts }, And again i have success

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.