You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Vue.js项目调用Laravel 5.6 API获取文章数据?

How to Configure Vue.js to Fetch Data from Laravel 5.6 API

Hey there! Let's get your Vue.js app pulling articles from your Laravel API smoothly. I’ve tackled this exact setup before, so here’s a step-by-step guide that works:

1. Fix CORS Issues First (Critical!)

Since your Vue app and Laravel API are separate, cross-origin requests will get blocked by default. For Laravel 5.6, the easiest way to handle this is with the barryvdh/laravel-cors package:

  • Install the package via Composer:
    composer require barryvdh/laravel-cors
    
  • Register the middleware in app/Http/Kernel.php:
    Add this line to the $middlewareGroups['api'] array (to apply it only to API routes):
    \Barryvdh\Cors\HandleCors::class,
    
  • Configure CORS settings:
    Publish the config file with:
    php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
    
    Then edit config/cors.php to allow your Vue app's domain. For local development, you can set:
    'allowed_origins' => ['http://localhost:8080'], // Your Vue dev server URL
    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'],
    'allowed_headers' => ['*'],
    

2. Verify Your Laravel API Route & Controller

Make sure your Laravel API is set up to return article data correctly:

  • Define the route in routes/api.php:
    Route::get('/articles', 'ArticleController@index');
    
  • In your ArticleController.php, write the index method to return JSON:
    public function index()
    {
        $articles = \App\Article::all(); // Or use a query to filter/sort as needed
        return response()->json($articles);
    }
    
    Test this route directly in your browser or Postman: http://your-laravel-domain/api/articles — you should see a JSON array of articles.

3. Set Up Axios in Your Vue.js Project

Axios is the go-to HTTP client for Vue apps. Let's set it up:

  • Install Axios via npm or yarn:
    npm install axios
    # Or
    yarn add axios
    
  • You can make it global in main.js for easy access across components:
    import Vue from 'vue'
    import axios from 'axios'
    
    Vue.prototype.$axios = axios
    

4. Fetch & Display Data in a Vue Component

Now let's write a component that fetches and shows the articles:

Create a component (e.g., ArticleList.vue):

<template>
  <div class="article-list">
    <h2>All Articles</h2>
    <div v-if="loading" class="loading">Loading articles...</div>
    <div v-else>
      <div v-for="article in articles" :key="article.id" class="article-card">
        <h3>{{ article.title }}</h3>
        <p>{{ article.excerpt }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      articles: [],
      loading: true
    }
  },
  created() {
    this.fetchArticles()
  },
  methods: {
    async fetchArticles() {
      try {
        const response = await this.$axios.get('http://your-laravel-domain/api/articles')
        this.articles = response.data
      } catch (error) {
        console.error('Failed to fetch articles:', error)
        alert('Oops, couldn’t load articles!')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

5. Optional: Use Environment Variables (Cleaner!)

To avoid hardcoding your API URL, use environment variables in Vue:

  • Create a .env file in your Vue project root:
    VUE_APP_API_URL=http://your-laravel-domain/api
    
  • Update the fetch call to use the variable:
    const response = await this.$axios.get(`${process.env.VUE_APP_API_URL}/articles`)
    

Quick Extra Tips

  • If your Laravel API requires authentication (e.g., with Sanctum), add the auth token to request headers:
    this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + yourAuthToken
    
  • For production, restrict your CORS allowed_origins to your production Vue domain instead of using * for security.

内容的提问来源于stack exchange,提问作者Emy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:33:12