【问题标题】:Got an error Invalid src prop ('here is a link') on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`在 `next/image` 上出现错误 Invalid src prop ('here is a link'),在 `next.config.js` 中的图像下未配置主机名“localhost”
【发布时间】:2021-03-02 16:29:48
【问题描述】:

我正在使用 Next.js 中的 Image 组件(它是 Next.js 的新功能)。我已尝试提供源 URL:

{`${API}/user/photo/${blog.postedBy.username}`}

但它向我显示了这个错误。我还在我的next.config.js 中进行了更改

module.exports = {
    images: {
      domains: ['localhost'],
    },
  }

但对我没有任何作用。如果您对此有所了解,请提供帮助。

【问题讨论】:

  • 什么API?是本地主机吗?
  • 是的,它是本地主机

标签: reactjs image next.js nextjs-image


【解决方案1】:
const src = `${API}/user/photo/${blog.postedBy.username}`;
    
<Image loader={() => src} src={src} width={500} height={500}/>

这里,loader 是一个为您的图片生成 URL 的函数。它将根域附加到您提供的 src,并生成多个 URL 以请求不同大小的图像。这些多个 URL 用于自动 srcset 生成,以便为您网站的访问者提供大小适合其视口的图像。

【讨论】:

    【解决方案2】:

    是的,我终于得到了答案。使 loader 函数从图像的目的地加载它。

    const myLoader=({src})=>{
      return `${API}/user/photo/${blog.postedBy.username}`;
    }
    

    将此加载器函数用于图像标签的加载器属性。

    <Image loader={myLoader} src={`${API}/user/photo/${blog.postedBy.username}`} width={500}
        height={500}/>
    

    这非常适合我

    【讨论】:

    • 行得通!我们也可以使用src参数,使其更加灵活:const myLoader=({src})=&gt;`${API}${src}`
    【解决方案3】:
    import Image from "next/image";
    
    
    <Image
        src="image path"
        alt="Picture of the author"
        width={500}
        height={500}
      />
    

    在公共文件夹中添加图片,然后给出 src 的路径,例如 src="/imageName.jpg" 添加宽度和高度

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,您需要重新启动开发服务器,每次对 next.config.js 文件进行更改时都需要这样做。

      API 字符串应包含端口。例如localhost:3001

      【讨论】:

        猜你喜欢
        • 2022-08-16
        • 2021-09-13
        • 2021-08-12
        • 2016-12-13
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        相关资源
        最近更新 更多