【问题标题】:How to allow all domains for Image nextjs config?如何允许 Image nextjs 配置的所有域
【发布时间】:2022-10-05 00:48:14
【问题描述】:

我有各种图像 url 并且随着时间的推移而变化(图像是通过 url 地址而不是本地或从私人存储中获取的)。为了呈现 <Image /> 标签,应该将域传递给 nextjs 配置。 无法通过 100s 的 url 超时。如何允许所有域?

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: [
      "img.etimg.com",
      "assets.vogue.com",
      "m.media-amazon.com",
      "upload.wikimedia.org",
    ],
  },
};

module.exports = nextConfig;

我试过这个,但不工作, "*.com"

【问题讨论】:

  • 另一种方法是使用 <img /> 标签而不是 Next JS <Image /> 标签。
  • 我目前正在使用普通的 img 标签,但我想使用 next 的 Image 标签来获得更好的优化。
  • 您可以尝试将正则表达式与 Loader nextjs.org/docs/api-reference/next/image#loader 一起使用

标签: next.js nextjs-image


【解决方案1】:

根据他们的文档,域必须是明确的

为了保护您的应用程序免受恶意用户的攻击,您必须定义一个您希望从 Next.js 图像优化 API 提供的图像提供程序域的列表。

您还可以看到源代码允许评估 url,不接受通配符。

https://github.com/vercel/next.js/blob/canary/packages/next/client/image.tsx#L864

解决

您应该查看像 cloudinary 或 imgix 这样的代理,并允许 next.config 中的这些域并使用它们的 fetch 功能加载外部图像。

IE

使用 cloudinary 作为允许的域

module.exports = {
  images: {
    domains: ['res.cloudinary.com'],
  },
};

然后在你的代码中

<Image
src="https://res.cloudinary.com/demo/image/fetch/https://a.travel-assets.com/mad-service/header/takeover/expedia_marquee_refresh.jpg"
width={500}
height={500}
/>

重要的

以下 StackBlitz 使用他们的演示帐户从 Expedia.com 获取外部图像,您应该获得自己的帐户用于生产。

https://stackblitz.com/edit/nextjs-pxrg99?file=pages%2Findex.js

【讨论】:

  • nextjs.org/docs/api-reference/next/image#loader-configuration,现在有一个专门的加载器选项。
  • 据我了解,该问题要求允许所有域 - 即使使用自定义 loader,您也必须明确说明 URL 字符串。
  • 是的,您建议将res.cloudinary.com 域列入白名单,然后使用fetch API。相反,您可以只使用 cloudinary 加载程序。然后无需将云 URL 附加到实际 URL。
【解决方案2】:

它适用于我,因此 next.js 文档:

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "**",
      },
    ],
  },
};

next.js remote patterns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2019-08-01
    • 2020-06-21
    • 2016-08-21
    • 2018-05-04
    • 2015-01-24
    • 2017-07-17
    相关资源
    最近更新 更多