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

Next.js 13实验版图片显示异常求助:无法加载Strapi远程图片

解决Next.js 13 App目录下Image组件无法加载Strapi远程图片问题

问题核心

配置remotePatterns后,Image组件仍请求本地/uploads/xxx.jpg而非Strapi后端地址,服务器返回text/html格式(多为Strapi的错误/登录页面),导致图片加载失败。

分步解决方案

1. 校验next.config.js的remotePatterns配置

确保配置包含完整的协议、主机、端口和路径匹配规则,示例如下:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: true,
  },
  images: {
    remotePatterns: [
      {
        protocol: 'http',
        hostname: '127.0.0.1',
        port: '1337',
        pathname: '/uploads/**', // 匹配/uploads下所有文件
      },
    ],
  },
}

module.exports = nextConfig

注意:port需为字符串类型,pathname的**用于匹配任意子路径。

2. 拼接完整的Strapi图片URL

Strapi API返回的图片地址通常是相对路径(如/uploads/xxx.jpg),需手动拼接Strapi的基础URL后传入Image组件:

// 从Strapi API获取的文章数据示例
const post = {
  attributes: {
    title: "示例标题",
    image: {
      data: {
        attributes: {
          url: "/uploads/xxx.jpg"
        }
      }
    }
  }
}

// 拼接完整URL
const strapiBaseUrl = "http://127.0.0.1:1337";
const fullImageUrl = `${strapiBaseUrl}${post.attributes.image.data.attributes.url}`;

在组件中使用:

import Image from 'next/image';

export default function Post() {
  return (
    <div>
      <h1>{post.attributes.title}</h1>
      <Image
        src={fullImageUrl}
        alt={post.attributes.title}
        width={600}
        height={400}
      />
    </div>
  )
}

3. 检查Strapi的文件访问权限

若Strapi未开放上传文件的公共访问权限,请求图片会返回登录页面(text/html格式),需:

  • 登录Strapi后台,进入Settings -> Users & Permissions Plugin -> Roles -> Public
  • 找到Upload权限,勾选find和findOne,保存设置

4. 清除缓存并重启服务

修改配置后,Next.js可能存在缓存残留,执行以下操作:

  • 删除项目根目录下的.next文件夹
  • 重启开发服务器:npm run dev

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:15