如何配置Vue.js项目调用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:
Then editphp artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"config/cors.phpto 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 theindexmethod to return JSON:
Test this route directly in your browser or Postman:public function index() { $articles = \App\Article::all(); // Or use a query to filter/sort as needed return response()->json($articles); }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.jsfor 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
.envfile 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_originsto your production Vue domain instead of using*for security.
内容的提问来源于stack exchange,提问作者Emy

