React+Laravel(Docker/WSL2)环境Axios请求HTTP 500错误求助
React + Laravel + WSL2 Docker 部署下Axios请求HTTP 500错误排查
使用React+Laravel开发应用,通过WSL2运行Docker容器部署,通过localhost访问时,Axios请求数据表接口持续返回HTTP 500错误,控制台无法打印返回数据。已尝试添加端口转发规则、更新防火墙规则,问题仍未解决。
相关配置信息
Windows PowerShell端口代理配置
PS C:\WINDOWS\system32> netsh interface portproxy show all Listen on ipv4: Connect to ipv4: Address Port Address Port --------------- ---------- --------------- ---------- 0.0.0.0 5173 172.29.39.95 172.17.0.1 172.18.0.1 5173 0.0.0.0 3306 172.29.39.95 172.17.0.1 172.18.0.1 3306 0.0.0.0 80 172.18.0.3 80
Laravel routes/api.php配置
<?php use App\Http\Controllers\CourseController; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\DataGeneratorController; Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum'); // routes/api.php // Route::get('/generate-data', [DataGeneratorController::class, 'createPseudoData']); // frontend axios connection Route::apiResource('courses', CourseController::class);
React App.jsx中的Axios代码
export default function App() { // backend testing to learn how the flip this works useEffect(() => { const fetchUsers = async () => { try { await axios .get('/api/courses') .then((response) => console.log(response)); } catch (error) { console.log('Error fetching users: ', error); } }; fetchUsers(); }, []); //... }
vite.config.ts配置
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import react from '@vitejs/plugin-react'; // need import line here to make tailwind work import tailwindcss from 'tailwindcss'; export default defineConfig({ css: { postcss: { plugins: [tailwindcss()] } }, plugins: [ laravel({ input: 'resources/js/app.tsx', refresh: true, }), react(), ], server: { hmr: { host: 'localhost', }, proxy:{ '/api': { target: 'http://172.18.0.1:3306', changeOrigin: true, headers: { Accept: 'application/json', "Content-Type": 'application/json' } } }, }, });
Dockerfile配置
# Dockerfile for Nginx FROM nginx:alpine # Expose port 80 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
排查建议
- 修正Vite代理目标:当前vite.config.ts中
/api代理指向http://172.18.0.1:3306,3306是MySQL端口,Laravel后端服务应运行在Web服务端口(如80)。将代理目标改为Laravel服务的实际地址,比如http://172.18.0.3:80(对应端口转发中80指向的容器地址)。 - 查看Laravel错误日志:进入WSL2的Laravel容器,查看
storage/logs/laravel.log文件,HTTP 500的具体错误原因会记录在这里(如数据库连接失败、控制器逻辑错误等)。 - 直接测试API接口:在WSL2内部用
curl http://localhost/api/courses测试后端接口,或在Windows浏览器访问http://localhost/api/courses,确认后端是否正常响应JSON数据。 - 检查数据库连接配置:Laravel的
.env文件中,数据库地址需配置为Docker容器服务名(而非localhost),比如MySQL容器名为mysql,则DB_HOST=mysql。 - 验证Nginx转发规则:当前Dockerfile仅启动Nginx,需确认Nginx配置文件是否包含反向代理Laravel服务的规则,确保请求能从Nginx转发到Laravel应用。
内容的提问来源于stack exchange,提问作者JBell
相关产品推荐
相关产品推荐

