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

Next.js 14加载Unsplash外部图片失败,求解决方案

Next.js 14加载Unsplash图片失败的解决方案
  • 完善remotePatterns配置
    Next.js的remotePatterns需要明确协议和路径匹配规则,仅设置hostname可能无法匹配具体图片路径。修改配置如下:

    const nextConfig = {
      images: {
        remotePatterns: [
          {
            protocol: "https",
            hostname: "images.unsplash.com",
            pathname: "/**", // 允许所有子路径匹配
          },
        ],
      },
      experimental: {
        serverActions: true,
      },
    };
    
    module.exports = nextConfig;
    
  • 检查Image组件的使用规范
    确保传入src的是完整的Unsplash图片HTTPS链接,且正确设置尺寸属性(或使用fill模式并为父容器设置相对定位):

    import Image from 'next/image';
    
    export default function ExamplePage() {
      return (
        <div style={{ position: 'relative', width: 500, height: 300 }}>
          <Image
            src="https://images.unsplash.com/photo-1506744038136-46273834b3fb"
            alt="Unsplash示例图片"
            fill
            objectFit="cover"
          />
        </div>
      );
    }
    
  • 清除Next.js缓存并重启服务
    运行以下命令清除缓存,再重启开发服务器:

    npx next clean
    npm run dev
    
  • 验证配置文件是否被正确加载
    在next.config.js中添加日志输出,重启服务后查看控制台是否打印配置信息,确认文件路径和文件名无误(必须是项目根目录下的next.config.js):

    const nextConfig = {
      // 你的配置内容
    };
    console.log('加载的Next.js配置:', nextConfig);
    module.exports = nextConfig;
    
  • 排查网络与跨域问题
    直接在浏览器中访问目标图片URL,确认图片能正常打开。如果无法访问,检查本地网络或代理设置;如果能访问但Next.js中仍无法加载,可尝试在next.config.js中添加unoptimized: true临时跳过图片优化(仅用于排查):

    images: {
      remotePatterns: [/* 你的配置 */],
      unoptimized: true,
    }
    

内容的提问来源于stack exchange,提问作者Ali.k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:42:19