Laravel+Vue使用Axios存储数据时遭遇401权限错误排查求助
Hey there, let's break down why you're hitting that 401 Unauthorized error when trying to save car details to your Laravel backend. First off, a quick clarification: 401 in Laravel almost always relates to authentication failure, not CSRF issues (those throw a 419 status code), so we can rule out your CSRF token setup for now.
Let's walk through the key fixes and checks:
1. Verify Your Route's Authentication Middleware
First, head to your routes/api.php file and confirm that the /api/car/store route is using an authentication middleware (like auth:sanctum for SPA/API auth):
Route::post('/car/store', [CarController::class, 'store'])->middleware('auth:sanctum');
If this middleware is applied, your request must include valid authentication credentials to pass through—without them, Laravel will return a 401.
2. Add Authentication Credentials to Your Axios Requests
Your current Bootstrap.js only configures the CSRF token, but it's missing the authentication token/cookie setup. Here are the two common scenarios:
Scenario A: SPA with Same-Domain Cookie Auth (Laravel Sanctum)
If your Vue app is hosted on the same domain as Laravel, Sanctum uses cookies for authentication. To make Axios automatically send these cookies:
- Update your
Bootstrap.jsto enable credentials:window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; // Add this line to allow Axios to send cookies with requests window.axios.defaults.withCredentials = true; let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found'); } - Also, ensure your
config/cors.phphas these settings:'supports_credentials' => true, 'allowed_origins' => ['http://your-frontend-domain.com'], // Match your Vue app's URL
Scenario B: Cross-Domain API with Token Auth (Sanctum API Tokens/Passport)
If your frontend is on a different domain, you'll need to send a Bearer token in the request header:
- Store the token you get from your login endpoint (e.g., in
localStorageor Vuex) - Add the Authorization header to your Axios config, either globally or per request:
Global setup (Bootstrap.js):
window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; let csrfToken = document.head.querySelector('meta[name="csrf-token"]'); if (csrfToken) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken.content; } // Add Bearer token from localStorage const authToken = localStorage.getItem('auth_token'); if (authToken) { window.axios.defaults.headers.common['Authorization'] = `Bearer ${authToken}`; }
Or per-request setup (in your Vue component):
saveCarDetails(){ let config = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` // Add this line } let currentObj = this; axios.post('/api/car/store', { user_id: currentObj.auth_user.id, car: currentObj.car }, config) .then(function (response) { console.log(response.data); }) .catch(function (error) { currentObj.error = error; // Fixed: Don't overwrite currentObj reference }) .then(() => { this.errors.clear(); }) }
3. Quick Code Fix Note
In your catch block, currentObj = error; will overwrite the currentObj reference to your Vue component. Change that to currentObj.error = error; if you want to store the error in your component's data.
4. Final Checks
- Make sure
currentObj.auth_user.idis not null/undefined—this confirms the user is actually logged in before sending the request. - If using Sanctum, ensure you've run
php artisan sanctum:installand configured your stateful domains inconfig/sanctum.php.
内容的提问来源于stack exchange,提问作者Sajid Latif

