【问题标题】:NextJs image component and jsonplaceholder external urlNextJs 图像组件和 jsonplaceholder 外部 url
【发布时间】:2023-01-31 02:11:45
【问题描述】:

在 nextJS 项目中,我想将 jsonplaceholder 与 /photos 路由一起使用。

当我尝试将图像或缩略图插入图像组件时,如下所示,出现错误。

import Image from 'next/image'
<Image src="https://via.placeholder.com/150/92c952" width={150} height={150} />

服务器错误

错误:无效的 src prop (https://via.placeholder.com/150/92c952) next/image, hostname "via.placeholder.com" 下没有配置 图片在你的next.config.js 查看更多信息: https://nextjs.org/docs/messages/next-image-unconfigured-host

当我检查外部资源的文档时,考虑到我使用的是最新版本 (13),我应该像这样转换我的 next.config.js :

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'via.placeholder.com',
        port: '',
        pathname: '/**',
      },
    ],
  },
}

module.exports = nextConfig

但是我仍然有错误,可能是因为空端口。但我不知道 via.placeholder.com 使用的是哪个端口 :(

使用下面的代码尝试旧的下一个版本也不起作用:

images: {
    domains: ['via.placeholder.com'],
  },

提前致谢

【问题讨论】:

    标签: next.js jsonplaceholder


    【解决方案1】:

    在为图像 src 使用字符串文字时,不需要使用花括号。你可以做类似&lt;Image src="https://cdn.architect.io/logo/horizontal.png" width={400} height={59.5} alt="Architect Logo" /&gt;的事情。此外,如果您使用 https 从服务器加载图像,则端口应为 443。有关更多上下文,我在 next.config.js 中添加了以下内容以加载我引用的图像:

    images: {
      remotePatterns: [
        {
          protocol: 'https',
          hostname: 'cdn.architect.io',
        },
      ],
    },
    

    此外,当尝试从 via.placeholder.com 加载 .png 时,请确保包含文件类型。例如:

    <Image src="https://via.placeholder.com/150/92c952.png" width={150} height={150} alt="Placeholder" />
    

    【讨论】:

    • 您好,感谢您的快速回答。对于花括号,我的错,这只是一个错误。真正的代码类似于 <Image src={data.thumbnailUrl} width={150} height={150} alt="foo" />。 443端口也不行
    • 如果我在 remotePattern 中省略了端口和路径,则会出现不同的错误。他加载了 alt 属性和我的服务器日志:via.placeholder.com/150/24f355 403 的上游图像响应失败(禁止)
    • 我已经更新了有关加载图像的更多详细信息的问题
    • 哦...给出的 URL 没有扩展名...与我的 next.config 文件和 "<Image src={data.thumbnailUrl + '.png'} width={150} height={150} alt=" 完美配合“ />”
    【解决方案2】:

    尽管其他答案中提到了设置(我测试了新的 images. remotePatterns 和旧的 images.domains),但都没有用。

    v13.0.7 升级到 v13.1.6 后,它现在可以工作了:)

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2020-12-06
      • 2021-09-14
      • 2012-04-03
      相关资源
      最近更新 更多