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

Next.js集成本地假期API返回404错误,该如何排查?

问题根因

  1. 环境变量未生效:修改env.local后没有重启Next.js开发服务,导致服务端运行的getServerSideProps读取不到NEXT_PUBLIC_API配置,axios的baseURL为空,请求默认发往http://localhost:80端口,和你实际运行的https://localhost:5001接口地址不符,触发404。可从报错信息里的responseUrl: 'http:/holiday?&country=ro&year=2021'验证该问题。
  2. 代码语法和逻辑错误:
    • index.ts中catch块语法错误,重复写了catch关键字
    • api.ts中请求路径硬编码了参数,没有使用传入的country、year变量,且query开头多了多余的&符号

修复方案

1. 修复api.ts代码

import axios from "axios";
import https from "https";
import { GetAllHolidaysData } from "../interfaces/GetAllHolidaysData";

const http = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API as string,
  // 开发环境如果本地接口是自签名https证书,加下面这行避免证书校验失败,生产环境删除
  httpsAgent: process.env.NODE_ENV === 'development' ? new https.Agent({ rejectUnauthorized: false }) : undefined
});

export const GetAllHolidays = (country: string, year: number) => {
  // 使用传入的动态参数,删除多余的&符号
  return http.get<GetAllHolidaysData>(
    `/holiday?country=${country}&year=${year}`
  );
};

2. 修复index.ts的catch块逻辑

export const getServerSideProps: GetServerSideProps = async () => {
  const country = "ro";
  const year = 2021;

  try {
    const { data } = await GetAllHolidays(country, year);
    console.log("接口返回数据:", data);
    // 把拿到的数据传递给页面组件
    return {
      props: {
        holidays: data.holidays,
      },
    };
  } catch (error) {
    console.error("接口请求失败:", error);
  }

  return {
    props: {
      holidays: [],
    },
  };
};

3. 生效配置

重启Next.js开发服务,确保env.local的配置被加载。重启前可以先直接在浏览器访问https://localhost:5001/api/holiday?country=ro&year=2021,确认本地接口可以正常返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:39:01