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

如何将Laravel搭建为Nuxt.js后端API?自建项目相关咨询

Got it, let's walk through setting up a clean Laravel + Nuxt.js project from scratch, focusing on configuring Laravel as a proper API backend and making smooth data transfers between the two. Here's a step-by-step guide:

1. Configure Laravel as an API Backend

First, let's get your Laravel app set up to act solely as an API (no frontend views):

1.1 Create a Fresh Laravel Project

Start with a minimal install to avoid unnecessary bloat:

composer create-project laravel/laravel my-api-backend
cd my-api-backend

1.2 Use API Routes Exclusively

Laravel includes an routes/api.php file dedicated to API endpoints—all routes here are automatically prefixed with /api. Example endpoints:

// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// Fetch all posts
Route::get('/posts', function (Request $request) {
    return response()->json([
        'posts' => [
            ['id' => 1, 'title' => 'First API Post'],
            ['id' => 2, 'title' => 'Second API Post']
        ]
    ]);
});

// Create a new post
Route::post('/posts', function (Request $request) {
    // Validate incoming data
    $validated = $request->validate([
        'title' => 'required|string|max:255'
    ]);

    // Replace with actual database logic (e.g., Post::create($validated))
    return response()->json(['message' => 'Post created successfully'], 201);
});

1.3 Enable CORS for Cross-Origin Requests

Since Nuxt runs on a different port (usually 3000) than Laravel (usually 8000), you need to allow cross-origin requests:

  1. Open config/cors.php
  2. Update paths to ['api/*'] to cover all API routes
  3. Set allowed_origins to ['http://localhost:3000'] (your Nuxt dev URL)
  4. Ensure allowed_methods includes ['GET', 'POST', 'PUT', 'DELETE']

Clear the config cache to apply changes:

php artisan config:cache

1.4 Force JSON Responses for API Errors

By default, Laravel redirects unauthenticated requests to a login page—we want JSON errors instead. For newer Laravel versions, update app/Http/Middleware/Authenticate.php:

protected function redirectTo($request)
{
    if (! $request->expectsJson()) {
        return response()->json(['message' => 'Unauthenticated.'], 401);
    }
}

1.5 Optional: Lightweight API Auth with Sanctum

If you need user authentication, Laravel Sanctum is perfect for SPA setups:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Follow Sanctum's docs to set up token or session-based auth—way lighter than Passport if you don't need OAuth.

2. Set Up Nuxt.js and Connect to Laravel API

Now let's build the Nuxt frontend and link it to your API:

2.1 Create a Minimal Nuxt Project

Start with a clean install (choose SPA mode for a simpler API-focused setup):

npx nuxi init my-nuxt-frontend
cd my-nuxt-frontend
npm install

2.2 Add Axios for API Requests

Axios is the standard for HTTP calls in Nuxt—install the official module for easy setup:

npm install @nuxtjs/axios

Configure it in nuxt.config.ts:

// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/axios'],
  axios: {
    baseURL: 'http://localhost:8000/api' // Your Laravel API base URL
  }
})

2.3 Fetch Data from Laravel

Use the useAxios composable to pull data in your Nuxt pages:

<!-- pages/index.vue -->
<template>
  <div>
    <h1>Posts from Laravel API</h1>
    <ul v-if="posts.length">
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
    <p v-else>No posts found</p>
  </div>
</template>

<script setup>
const { data: posts } = await useAxios('/posts')
</script>

2.4 Send Data to Laravel

Make POST requests to submit data to your API endpoints:

<!-- pages/create-post.vue -->
<template>
  <div>
    <input v-model="postTitle" placeholder="Enter post title" />
    <button @click="createPost">Create Post</button>
  </div>
</template>

<script setup>
const postTitle = ref('')
const { $axios } = useNuxtApp()

const createPost = async () => {
  try {
    const response = await $axios.post('/posts', {
      title: postTitle.value
    })
    alert(response.data.message)
    postTitle.value = ''
  } catch (error) {
    console.error('Error creating post:', error.response.data)
  }
}
</script>
3. Keep Dependencies Lean

To avoid the bloat you encountered in the template:

  • For Laravel: Only install packages you actually need (e.g., Sanctum for auth, skip unused utilities).
  • For Nuxt: Stick to official modules and enable tree-shaking where possible. For Vuetify, use the official Nuxt module with tree-shaking:
    npm install @nuxtjs/vuetify
    
    Add this to nuxt.config.ts:
    export default defineNuxtConfig({
      modules: ['@nuxtjs/axios', '@nuxtjs/vuetify'],
      vuetify: {
        treeShake: true
      }
    })
    
Final Quick Tips
  • Run Laravel with php artisan serve (starts on http://localhost:8000)
  • Run Nuxt with npm run dev (starts on http://localhost:3000)
  • Test API endpoints with Postman/Insomnia first to confirm they work before linking to Nuxt.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:17:06