Laravel 5.5虚拟主机子目录下Axios API请求异常求助
Hey there! I’ve run into this exact issue before when deploying Laravel apps to subfolders on shared hosting. The good news is you don’t have to manually add the subfolder path to every Axios request—here are a few cleaner solutions:
1. Set Axios Base URL Globally
The simplest fix is to configure Axios to automatically prepend your subfolder path to all requests. Just add this line to your app.js (or bootstrap.js if you’re using that):
// Add this at the top of your app.js axios.defaults.baseURL = '/your-subfolder-name';
Once you do this, any Axios request like axios.get('/oauth/clients') will automatically resolve to https://domainname/your-subfolder-name/oauth/clients—no more manual path edits needed!
2. Use Laravel’s Dynamic URL for Environment Flexibility
If you switch between local development (root directory) and production (subfolder), hardcoding the subfolder isn’t ideal. Instead, pass the app’s base URL from Laravel to your frontend:
In your main Blade template (e.g.,
resources/views/layouts/app.blade.php), add this script before loadingapp.js:<script> window.appBaseUrl = "{{ url('/') }}"; </script>Then update your
app.jsto use this dynamic value:axios.defaults.baseURL = window.appBaseUrl;
This way, Laravel will automatically inject the correct base URL (whether it’s http://localhost locally or https://domainname/your-subfolder in production) and Axios will use it for all requests.
3. Verify Virtual Host Configuration (Optional)
If you have access to your virtual host settings, you can set the DocumentRoot directly to your Laravel app’s public folder inside the subfolder. For example, in Apache:
<VirtualHost *:443> ServerName domainname DocumentRoot /path/to/your/subfolder/public <Directory /path/to/your/subfolder/public> AllowOverride All Require all granted </Directory> </VirtualHost>
This makes your Laravel app act as the root for that subfolder, so you won’t need to modify Axios at all. This is the cleanest long-term solution if you have hosting access.
Why This Happens
Local development runs Laravel at your server’s root (e.g., http://localhost), so Axios requests to /oauth/clients work fine. But when deployed to a subfolder, those requests still target the domain root (https://domainname/oauth/clients) instead of the subfolder where your Laravel routes actually live.
内容的提问来源于stack exchange,提问作者Roy Gallardo

