Next.js 14使用next/image组件无法加载localhost:8081图片
Next.js 14中next/image无法加载本地Java后端图片的问题
在Next.js 14项目中,使用next/image组件加载localhost:8081(Java后端提供)的图片时出现错误,但使用普通<img>标签能正常显示。
相关代码片段
'use client' import Image from 'next/image' export default function Home() { return ( <div className='flex items-center justify-center min-h-screen'> <Image src={'http://localhost:8081/api/image/get/1'} alt='image' width={200} height={200} /> Hello world!!! </div> ) }
已尝试的配置(未解决问题)
/** @type {import('next').NextConfig} */ const nextConfig = { image: { remotePatterns: [ { protocol: 'http', hostname: 'localhost', port: '8081', pathname: '/api/image/get/**', }, ], }, } export default nextConfig
解决方法
- 修正配置项名称:Next.js的图片远程资源配置项是复数形式的
images,你当前配置中的image(单数)不生效,修正后的配置如下:
/** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: 'http', hostname: 'localhost', port: '8081', pathname: '/api/image/get/**', }, ], }, } export default nextConfig
- 修正后重启Next.js开发服务器,确保配置生效。
- 若问题仍存在,检查后端返回的图片响应头是否包含正确的
Content-Type(如image/jpeg、image/png),next/image对响应类型要求更严格,而普通<img>标签兼容性更强。
内容的提问来源于stack exchange,提问作者Mahkambek Satimov
相关产品推荐
相关产品推荐

