Docker+Laravel+Vue环境下Axios请求出现ERR_NETWORK错误求助
问题:Docker部署Laravel+Vue应用登录时出现Axios ERR_NETWORK错误
尝试登录时控制台报错:
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code: "ERR_NETWORK"
完整错误信息:
{ "message": "Network Error", "name": "AxiosError", "stack": "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=6e20bfbd:1454:14)", "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, ..... "code": "ERR_NETWORK", "status": null }
已知后端服务正常,通过http://localhost:8000/api/loan可正常获取数据库数据,但前端通过配置的VITE_API_URL发送请求时失败。
我的配置代码
Dockerfile
FROM php:8.3.4-apache as web RUN apt-get update -y RUN apt-get install -y unzip zip libpq-dev libcurl4-gnutls-dev libicu-dev nano libzip-dev RUN docker-php-ext-configure intl # PHP extensions RUN docker-php-ext-install pdo pdo_mysql bcmath intl zip # Mod Rewrite RUN a2enmod rewrite # Composer COPY --from=composer:2.7.2 /usr/bin/composer /usr/bin/composer WORKDIR /var/www/html # apache config COPY ./Docker/apache.conf /usr/local/apache2/conf/httpd.conf COPY . . COPY entrypoint.sh /usr/local/bin/entrypoint.sh RUN chmod +x /usr/local/bin/entrypoint.sh RUN chown -R www-data:www-data /var/www/html/storage RUN chmod -R 777 /var/www/html/storage ENTRYPOINT [ "entrypoint.sh" ] # ===== NODE ===== NODE ===== NODE ===== NODE ===== NODE ===== FROM node:20.12.0 as node WORKDIR /var/www/html/ COPY . . RUN npm install --global cross-env VOLUME /var/www/html/node_modules CMD ["npm", "run", "dev"]
docker-compose.yml
version: "3.8" services: # Web Service web: container_name: ibi_system_app_test depends_on: - database - node build: context: . target: web args: - APP_ENV=${APP_ENV} environment: - APP_ENV=${APP_ENV} - CONTAINER_ROLE=app volumes: - ./:/var/www/html ports: - 8000:80 hostname: ${HOST_NAME} domainname: ${APP_URL} # Database Server database: container_name: database_test image: mysql:8.0 ports: - 3306:3306 environment: - MYSQL_DATABASE=${DB_DATABASE} - MYSQL_USER=${DB_USERNAME} - MYSQL_PASSWORD=${DB_PASSWORD} - MYSQL_ROOT_PASSWORD=${DB_PASSWORD} volumes: - db-data:/var/lib/mysql # Node Server node: container_name: node_test build: context: . target: node volumes: - ./node_modules:/usr/src/node_modules tty: true ports: - 5173:5173 # Expose Vite port # PHP myadmin phpmyadmin: container_name: phpmyadmin_test depends_on: - database image: phpmyadmin/phpmyadmin environment: - PMA_HOST=database - PMA_PORT=3306 ports: - 8001:80 volumes: db-data: ~
entrypoint.sh
#!/bin/bash echo "test." if [ ! -f "vendor/autoload.php" ]; then echo "Installing composer dependencies." composer install --no-progress --no-interaction fi if [ ! -f ".env" ]; then echo "Creating env file for env $APP_ENV" cp .env.example .env else echo "env file exists." fi role=${CONTAINER_ROLE:-app} echo "role - $role" if [ "$role" = "app" ]; then php artisan migrate php artisan key:generate php artisan view:clear php artisan cache:clear php artisan config:clear php artisan route:clear apache2-foreground fi
apache.conf
<VirtualHost *:80> ServerAdmin webmaster@ibi-system-test DocumentRoot "/var/www/html/public" ServerName ibi-system-test ServerAlias www.ibi-system-test <Directory "/var/www/html/public"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
Vite配置
/* eslint-disable import/no-extraneous-dependencies */ import { defineConfig } from "vite"; import laravel from "laravel-vite-plugin"; import vue from "@vitejs/plugin-vue2"; import postcss from "./postcss.config"; export default defineConfig({ plugins: [ laravel({ input: ["resources/js/app.js"], postcss, refresh: true, }), vue(), ], define: { "process.env": process.env, }, resolve: { alias: { vue: "vue/dist/vue.esm.js", "~": "/resources/js", }, }, server: { host: true, port: 5173, hmr: { host: "localhost" }, }, });
.env文件
APP_NAME=ibi_system_app_test APP_ENV=development APP_KEY=.... APP_DEBUG=true APP_URL=http://ibi-system-test VITE_APP_URL=http://ibi-system-test VITE_API_URL=http://ibi-system-test/api HOST_NAME=ibi-system-test
登录请求代码
import axios from "axios"; import useLoaderStore from "../../stores/LoaderStore"; const { VITE_API_URL } = import.meta.env; export default async (requestBody) => { const loaderStore = useLoaderStore(); try { loaderStore.showLoader(); console.log(VITE_API_URL); // 打印结果为 http://ibi-system-test/api const logIn = await axios.post(`${VITE_API_URL}/login`, requestBody); // 触发错误 console.log(logIn); const { data } = logIn; return data; } catch (error) { // eslint-disable-next-line no-console console.log(error); // 打印错误 console.log(error.response.data); return error.response.data; } finally { loaderStore.hideLoader(); } };
解决方案
问题核心是前端浏览器无法解析ibi-system-test域名,或请求地址与当前页面域名不一致导致跨域,按以下步骤解决:
1. 配置本地hosts解析域名
在本地系统的hosts文件中添加一行映射,让浏览器能识别ibi-system-test:
127.0.0.1 ibi-system-test
- Windows路径:
C:\Windows\System32\drivers\etc\hosts - macOS/Linux路径:
/etc/hosts
2. 直接修改VITE_API_URL为本地端口
如果不想配置hosts,直接修改.env文件中的API地址为Docker映射的本地端口:
VITE_API_URL=http://localhost:8000/api
3. 配置Laravel跨域(若仍有跨域问题)
若修改后出现跨域报错,安装并配置CORS中间件:
- 安装依赖包:
composer require fruitcake/laravel-cors
- 修改
config/cors.php,允许前端域名:
return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://localhost:5173', 'http://ibi-system-test:5173'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ];
- 在
app/Http/Kernel.php的api中间件组中添加CORS处理:
protected $middlewareGroups = [ 'api' => [ \Fruitcake\Cors\HandleCors::class, // 其他中间件... ], ];
4. 重启Docker容器
修改配置后,重启容器使所有设置生效:
docker-compose down && docker-compose up -d
内容的提问来源于stack exchange,提问作者yakov
相关产品推荐
相关产品推荐

