You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js调用Strapi接口报TypeError: fetch failed错误求助

解决Next.js getServerSideProps中无法连接Strapi 1337端口的问题

核心原因

getServerSideProps在Node.js服务器环境中执行,这里的localhost和客户端(Postman)的localhost上下文可能不一致;或者Strapi未配置为允许外部访问,导致服务器端请求被拒绝。

排查解决步骤

1. 修改Strapi监听地址,允许外部访问

默认情况下Strapi可能仅监听127.0.0.1,仅允许本机客户端访问,服务器端请求(如Next.js的Node进程)无法连接。修改Strapi配置:

  • 打开Strapi项目的config/server.js(或config/env/development/server.js)
  • 将host字段改为"0.0.0.0":
    module.exports = ({ env }) => ({
      host: env('HOST', '0.0.0.0'),
      port: env.int('PORT', 1337),
      app: {
        keys: env.array('APP_KEYS'),
      },
    });
    
  • 重启Strapi服务,确保配置生效。

2. 替换localhost为宿主机器IP(开发环境)

如果是本地开发且使用WSL、Docker等环境,Next.js服务器端的localhost指向容器/子系统本身,而非宿主机器。此时:

  • 找到宿主机器的局域网IP(如192.168.1.100)
  • 将请求地址替换为该IP:
    export async function getServerSideProps() {
      const insightsResponse = await fetcher(
        "http://192.168.1.100:1337/api/insights"
      );
      return {
        props: {
          insights: insightsResponse,
        },
      };
    }
    

3. 使用环境变量管理API地址

避免硬编码地址,提升代码可移植性:

  • 在Next.js项目根目录创建.env.local文件:
    NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
    
  • 在代码中读取环境变量:
    export async function getServerSideProps() {
      const apiUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL;
      const insightsResponse = await fetcher(`${apiUrl}/api/insights`);
      return {
        props: {
          insights: insightsResponse,
        },
      };
    }
    

4. 验证Strapi端口状态

确认Strapi确实在1337端口运行:

  • Mac/Linux终端执行:lsof -i :1337,查看是否有Strapi进程占用该端口
  • Windows命令提示符执行:netstat -ano | findstr :1337,检查进程ID并确认是Strapi

5. 优化fetcher函数的错误处理

原fetcher函数存在冗余逻辑,且未处理HTTP错误状态,优化后:

export async function fetcher(url: string, options = {}) {
  const response = await fetch(url, options);
  // 处理HTTP错误(如404、500)
  if (!response.ok) {
    throw new Error(`请求失败,状态码:${response.status}`);
  }
  const data = await response.json();
  return data;
}

内容的提问来源于stack exchange,提问作者CIB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:10:37