Laravel/Vue跨虚拟机部署API请求失败问题解决方案咨询
Client-side Vue runs in end users' browsers, which can't directly access your backend's private IP (it's only reachable within your internal network). The frontend server can communicate with the backend, so we need to route API requests through the frontend server to bridge this gap.
This is the most straightforward fix for your setup:
Enable Required Apache Modules
Run these commands on your frontend Ubuntu server to enable proxy functionality:sudo a2enmod proxy proxy_http proxy_balancer lbmethod_byrequestsConfigure Frontend Apache Virtual Host
Edit your frontend's Apache site config (e.g.,/etc/apache2/sites-available/your-public-domain.conf) and add proxy rules for API requests:<VirtualHost *:80> ServerName your-public-domain.com # Serve Vue static files (adjust path to your Vue dist folder) DocumentRoot /var/www/vue-app/dist # Proxy all /api requests to backend's private IP ProxyPass /api http://backend-private-ip/api ProxyPassReverse /api http://backend-private-ip/api <Directory /var/www/vue-app/dist> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/vue-app-error.log CustomLog ${APACHE_LOG_DIR}/vue-app-access.log combined </VirtualHost>Replace
backend-private-ipwith your actual backend VM's private IP (e.g.,192.168.1.100).Update Vue Axios Base URL
In your Vue app, set Axios to use a relative path for API calls (so it routes through the frontend server):import axios from 'axios'; axios.defaults.baseURL = '/api';Rebuild your Vue app and deploy the updated
distfolder to the frontend server.Restart Apache
Apply the config changes:sudo systemctl restart apache2
- Don't use
php artisan servefor backend: Set up Apache/Nginx on your backend VM to serve Laravel. For Apache, configure a virtual host pointing to Laravel'spublicdirectory. - Firewall Rules: Ensure your backend VM's firewall allows incoming traffic on port 80 (or your backend web server port) from the frontend VM's private IP.
内容的提问来源于stack exchange,提问作者Muhammad maged

