NextJS v13.4.19调用Strapi v4.12.5接口出现fetch failed错误求助
NextJS 调用 Strapi 接口出现 ECONNREFUSED 错误排查方案
问题描述
我正在开发基于 NextJS v13.4.19 和 Strapi v4.12.5 的应用,使用 fetch 调用 Strapi 接口时遇到连接拒绝错误。已尝试以下方案但均无效:
- 将请求地址从
localhost:1337改为127.0.0.1:1337 - 切换 Strapi 后端的 Node.js 版本为 14/16/18
- 将 Strapi 的 fetch 请求迁移至 NextJS 的
api目录下
测试调用随机公开 JSON 接口可正常工作,因此问题大概率与 Strapi 相关。
相关代码
import React from "react"; export const getItems = async () => { try { const wearResponse = await fetch( `http://localhost:1337/api/items/?populate=*` ); // 此处抛出异常 if (!wearResponse.ok) throw new Error("获取商品失败"); return wearResponse.json(); } catch (err: any) { console.error("发生错误:", err); } }; export default async function Page() { const itemsList = await getItems(); return ( <> <h2>...</h2> </> ); }
报错信息
发生错误: TypeError: fetch failed ... { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 1337 }
排查步骤与解决方案
1. 确认 Strapi 服务状态
- 查看 Strapi 控制台日志,确认是否输出
Server is running on http://localhost:1337类的启动成功信息 - 直接在浏览器访问
http://localhost:1337/api/items/?populate=*:- 若浏览器也无法访问,说明 Strapi 未启动或端口被占用,先解决服务启动问题
- 若浏览器能访问但 NextJS 不行,继续排查后续步骤
2. 配置 Strapi 跨域规则
Strapi 默认可能限制跨域请求,修改 config/middlewares.js 中的 CORS 配置:
module.exports = [ // ...其他中间件 { name: 'strapi::cors', config: { origin: ['http://localhost:3000'], // 替换为你的 NextJS 运行端口 methods: ['GET', 'POST', 'PUT', 'DELETE'], credentials: true, }, }, // ...其他中间件 ];
修改后重启 Strapi 服务。
3. 检查网络环境适配
- 若使用 Docker/容器运行服务,
localhost指向容器内部而非宿主机,需替换为宿主机实际 IP(如192.168.x.x:1337) - 临时关闭本地防火墙,测试是否是防火墙拦截了 1337 端口的请求
4. 验证 Strapi 端口配置
- 查看 Strapi 项目根目录
.env文件,确认是否存在PORT=1337配置,若端口已修改,同步更新 NextJS 请求地址 - 使用
netstat -ano | findstr :1337(Windows)或lsof -i :1337(Mac/Linux)检查端口是否被其他进程占用
5. 代码优化建议
- 用环境变量存储 Strapi 地址,避免硬编码:
在 NextJS 项目的.env.local文件中添加:
代码中修改为:NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337const wearResponse = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API_URL}/api/items/?populate=*`); - 增强错误日志输出,方便定位:
catch (err: any) { console.error("请求错误详情:", err.message, err.cause); }
内容的提问来源于stack exchange,提问作者Telirw
相关产品推荐
相关产品推荐

