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

NextJS使用SWR请求API出现路径重复,如何获取正确请求路径?

解决NextJS+SWR请求路径重复问题

你的问题出在请求地址缺少协议前缀(http://),导致fetch将其识别为相对路径,自动拼接到NextJS本地服务地址(http://localhost:3000)后,才出现了路径重复的情况。

下面是具体修复方案:

方案一:在.env中配置完整API基础地址

修改.env文件,直接写入带协议的完整基础地址:

API_BASE_URL=http://127.0.0.1:8000

然后在tsx中拼接接口路径:

'use client'
import useSWR from "swr";
import HomeOutstanding from "@/components/partials/home/HomeOutstanding";

const fetcher = (url: string) => fetch(url).then((res) => res.json());

// 用完整基础地址拼接接口路径
const API_POST_POPULAR = `${process.env.API_BASE_URL}/api/posts/get-five-post-popular?skip=0&limit=5`

export default function Home() {
  const { data, error, isLoading} = useSWR(API_POST_POPULAR, fetcher)
  
  if (isLoading) {
    return <div>Loading...</div>
  }
  if (error) {
    return <div>Failed to api</div>
  }
  if (!data) {
    return <div>Loading</div>
  }
  
  // 补充组件渲染逻辑
  return <HomeOutstanding data={data} />
}

方案二:保留原.env结构,拼接时补充协议前缀

如果不想修改.env配置,就在拼接地址时手动添加http://前缀:

'use client'
import useSWR from "swr";
import HomeOutstanding from "@/components/partials/home/HomeOutstanding";

const fetcher = (url: string) => fetch(url).then((res) => res.json());

// 添加http://前缀确保是绝对路径
const API_POST_POPULAR = `http://${process.env.API_URL}:${process.env.API_PORT}/api/posts/get-five-post-popular?skip=0&limit=5`

export default function Home() {
  const { data, error, isLoading} = useSWR(API_POST_POPULAR, fetcher)
  
  if (isLoading) {
    return <div>Loading...</div>
  }
  if (error) {
    return <div>Failed to api</div>
  }
  if (!data) {
    return <div>Loading</div>
  }
  
  // 补充组件渲染逻辑
  return <HomeOutstanding data={data} />
}

两种方案都能让请求地址变为预期的http://127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5,避免相对路径导致的地址重复问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:02:31