Next.js SSR调用Laravel API出现ECONNREFUSED连接拒绝问题
解决Next.js SSR模式下Axios调用Laravel API的连接拒绝问题
问题核心
前端浏览器环境下可正常与Laravel API通信,但Next.js在SSR(服务端渲染)时通过Axios调用API,出现connect ECONNREFUSED ::1:443或127.0.0.1:443连接拒绝错误。
常见原因及解决方案
1. Docker容器内无法访问宿主机的127.0.0.1
Docker容器内的127.0.0.1指向容器自身,而非宿主机。若SSR时Axios配置的API地址为https://127.0.0.1或https://localhost,容器无法访问到宿主机的Nginx反向代理。
解决办法:
- 使用Docker Compose中Laravel服务的名称作为API地址(例如Laravel服务名为
laravel-api,则用http://laravel-api/api),容器间通信直接走HTTP即可,无需HTTPS(Nginx的HTTPS仅对外网请求生效)。 - 示例Axios配置:
const apiClient = axios.create({ baseURL: process.env.NODE_ENV === 'production' ? 'https://your-domain.com/api' : 'http://laravel-api/api', withCredentials: true });
2. Nginx配置强制HTTPS导致内部请求失败
若Nginx强制所有请求跳转到HTTPS,但容器间通信走HTTP,会引发重定向循环或连接问题。
调整Nginx配置:
针对Docker子网的内部请求,跳过HTTPS重定向:
server { listen 80; server_name your-domain.com; # 仅对非Docker子网的请求重定向到HTTPS if ($remote_addr !~ ^172\.(1[6-9]|2[0-9]|3[0-1])\.) { return 301 https://$server_name$request_uri; } location /api { proxy_pass http://laravel-api:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
3. SSR时Axios未正确传递Cookie
服务端环境的Axios无法直接获取浏览器Cookie,需手动从请求头中提取并传递给API。
解决办法:
在Next.js的getServerSideProps中传递Cookie:
export async function getServerSideProps(context) { const { req } = context; const apiClient = axios.create({ baseURL: 'http://laravel-api/api', headers: { Cookie: req.headers.cookie || '' }, withCredentials: true }); try { const response = await apiClient.get('/some-endpoint'); return { props: { data: response.data } }; } catch (error) { console.error(error); return { props: {} }; } }
4. Laravel CORS配置未允许SSR服务访问
确保Laravel的CORS配置允许Next.js服务端的地址,且开启凭据支持。
修改config/cors.php:
return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['https://your-nextjs-domain.com', 'http://nextjs-service:3000'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ];
错误日志分析
connect ECONNREFUSED ::1:443明确说明SSR时Axios请求尝试连接容器自身的443端口,但你的Nginx或Laravel API并未在容器内的443端口运行,核心修正点是将API地址改为Docker内部可访问的服务名或IP。
内容的提问来源于stack exchange,提问作者Juan Pablo B
相关产品推荐
相关产品推荐

