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

Laravel+Vue使用Axios存储数据时遭遇401权限错误排查求助

Fixing 401 Unauthorized Error When Saving Data via Axios to Laravel

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:

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.js to 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.php has 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 localStorage or 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.id is 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:install and configured your stateful domains in config/sanctum.php.

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

相关产品推荐
方舟 Agent Plan

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

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