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

NextJS API返回图片无法显示问题排查求助

NextJS图片无法显示问题的修复方案

问题根源及修复点

  • 静态资源路径错误:NextJS的public文件夹是静态资源的根目录,访问其中的文件不需要带/public前缀。你当前API返回的image路径包含/public,导致资源无法被正确定位。
  • Image组件参数错误:
    • 本地静态资源无需自定义loader,NextJS默认loader会自动处理public目录下的资源,自定义loader反而会干扰路径解析。
    • height属性需传入数字类型,你使用的字符串值不符合组件要求。
  • 类型定义不匹配:CartTypeItem中定义的amount字段在API返回数据中不存在,会引发类型警告,需同步调整类型或补充字段。

修正后的代码

pages/api/data.tsx

import type { NextApiRequest, NextApiResponse } from 'next'

type Data = { 
  id: number,
  name: string,
  description: string, 
  image: string,
  price: number
}[]

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json(
    [
      {
        id: 1,
        name: "pump control",
        image: "/automatic.png", // 移除/public前缀
        price: 20000,
        description: "automatic pressure control for water regulator"
      },
      {
        id: 2,
        name: "Automatic pump control",
        image: "/pump.png", // 移除/public前缀
        price: 20000,
        description: "automatic pressure control for water regulator"
      }
    ]
  )
}

items.tsx

import axios from "axios"
import useSWR from "swr"
import Image from "next/image"
import { useRouter } from "next/router"

// 移除未使用的amount字段,保持类型与API返回一致
export type CartTypeItem = {
  id: number
  name: string
  image: string
  price: number 
  description: string 
}

const Items: React.FC = () => {
    const fetcher = (apiUrl: string) => axios.get(apiUrl).then(res => res.data)
    const router = useRouter()

    const { data, error } = useSWR<CartTypeItem[]>("http://localhost:3000/api/data/", fetcher)

    console.log(data)

  return (
    <div>
        {data?.map(item => (
          <div key={item.id}>
            {/* 移除自定义loader,将height改为数字类型 */}
            <Image src={item.image} alt={item.name} width={100} height={70} />
          </div>
        ))}
    </div>
  )
}

export default Items

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:15:35