如何在Next JS中引用Strapi API返回的图片并使用Image组件渲染
Next.js 加载 Strapi 动态图片解决方案
1. 核心报错原因
- 图片路径嵌套层级取值错误,拿到
undefined拼接后路径无效 - Next.js 内置
Image组件未配置远程图片域名白名单 - 路径拼接时出现重复斜杠、空值未兼容导致404
- 服务端渲染阶段未做空值判断,触发编译报错
2. 分步解决方法
2.1 配置Next.js图片域名白名单
修改项目根目录的next.config.js文件,添加Strapi本地服务域名配置:
/** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: 'http', hostname: 'localhost', port: '1337', // 替换为你的Strapi实际运行端口 pathname: '/uploads/**', }, ], }, } module.exports = nextConfig
修改配置后需要重启Next.js服务生效。
2.2 封装Strapi资源路径拼接工具
新建工具函数统一处理路径拼接,兼容空值、避免重复斜杠问题:
// utils/strapi.js export const getStrapiMedia = (mediaUrl) => { // 空值返回占位图,避免报错 if (!mediaUrl) return "/default-placeholder.png"; // 已经是完整路径直接返回 if (mediaUrl.startsWith("http")) return mediaUrl; // 拼接前去除首尾多余斜杠,避免路径重复斜杠问题 const baseUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL.replace(/\/$/, ""); const path = mediaUrl.replace(/^\//, ""); return `${baseUrl}/${path}`; };
在项目根目录.env.local中配置Strapi服务地址:
NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
2.3 正确取值与渲染
Strapi返回的图片嵌套层级固定为字段名.data.attributes.url,使用可选链避免空值报错:
import Image from "next/image"; import { getStrapiMedia } from "@/utils/strapi"; // 渲染示例 const ArticleCard = ({ articleData }) => { const imgUrl = getStrapiMedia( articleData?.attributes?.titlePicture?.data?.attributes?.url ); return ( <div> <Image src={imgUrl} alt="标题图" width={800} height={400} /> </div> ) };
内容的提问来源于stack exchange,提问作者Ibo
相关产品推荐
相关产品推荐

