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

NextJS+Strapi中使用Axios获取数据报错求助

解决Axios连接Strapi时出现ECONNREFUSED错误

我已经完成以下操作:

  • 部署Strapi项目
  • 部署NextJS项目
  • 安装并配置Axios以从Strapi后端获取数据

但调用接口时持续出现连接拒绝错误,相关代码如下:

import axios from "axios"  // axios已安装

const DashboardHome = () => {
  return (
    <div>
      ...
    </div>
  );
};
export async function getServerSideProps(context) {
  const baseUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL;  // 配置的url: 'http://localhost:1337/api/users'

  try {
    const { data } = await axios.get(`${baseUrl}/users`, {
      headers: {
        Authorization: `bearer ${process.env.NEXT_PUBLIC_FORGEDMART_STRAPI_API_TOKEN}`,
      },
    });
    console.log(data);
  } catch (error) {
    console.log(error);
  }

  return {
    props: {
      {...}
    },
  };
}

返回的错误内容:

// 错误信息
AxiosError: connect ECONNREFUSED ::1:1337 {
  port: 1337,
  address: '::1',
  errno: -61,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    headers: AxiosHeaders {
      Authorization: 'bearer udududhdhdhdhd83838383',
      'User-Agent': 'axios/1.1.3',
    },
    method: 'get',
    url: 'http://localhost:1337/api/users',
    data: undefined
  },

可行的解决办法

  • 确认Strapi服务是否正常运行:先在本地终端执行curl http://localhost:1337/api/users,看能不能正常返回数据。如果Strapi没启动,先启动服务;如果1337端口被占用,修改Strapi配置换个端口。
  • 把localhost换成127.0.0.1:错误里显示连接的是IPv6地址::1,有些环境下IPv6解析会出问题。把环境变量NEXT_PUBLIC_STRAPI_API_URL改成http://127.0.0.1:1337/api,强制用IPv4访问。
  • 配置Strapi的跨域规则:如果NextJS和Strapi不在同一环境(比如NextJS部署在云端,Strapi在本地),需要在Strapi的config/middlewares.js里设置CORS,允许NextJS的域名访问。示例配置:
module.exports = [
  // 保留其他原有中间件
  {
    name: 'strapi::cors',
    config: {
      origin: ['你的NextJS项目域名'],
      methods: ['GET', 'POST', 'PUT', 'DELETE'],
      credentials: true,
    },
  },
];
  • 检查API Token的权限:虽然当前是连接错误,但可以顺带确认Strapi的API Token是否拥有users集合的读取权限,避免后续遇到权限问题。
  • 容器部署的网络适配:如果用Docker部署Strapi和NextJS,不能用localhost访问Strapi,要改用容器名称或者Docker内部网络地址,比如http://strapi-container:1337/api。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:55:14