【问题标题】:How to upload a photo with React and Next?如何使用 React 和 Next 上传照片?
【发布时间】:2021-12-14 03:33:00
【问题描述】:

我是 React 和 Next 的初学者,我开始从事这个项目。我有一个功能需要上传个人资料图片,但每当我上传图片时,都会触发错误。

错误:next/image 上的 src prop (http://localhost:3333/files/ SOME IMAGE.jpg) 无效,主机名“localhost”未在您的 next.config.js 中的图像下配置 查看更多信息:https://nextjs.org/docs/messages/next-image-unconfigured-host

.next\static\chunks\pages\_app.js (604:22) @ defaultLoader

  602 |         }
  603 |         if (process.env.NODE_ENV !== 'test' && !configDomains.includes(parsedSrc.hostname)) {
> 604 |             throw new Error(`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`);
      |                  ^
  605 |         }
  606 |     }
  607 | }

我的next.config.js

module.exports = {
  images: {
    domains: [process.env.API_STORAGE_DOMAIN]
  }
}

【问题讨论】:

  • 您可以在 Next.js 应用程序的根目录中创建 next.config.js
  • 嗨@juliomalves!我更新了我的问题,你能看一下吗?
  • 您是否仍然看到完全相同的错误? process.env.API_STORAGE_DOMAIN 有什么价值?
  • @juliomalves 是的,.env 是 .env.production.env.development,在这个文件里面有:API_STORAGE_DOMAIN=the-project-name-bucket.s3.amazonaws.com
  • 您正在设置 s3 存储桶域,但错误提示未配置 localhost"hostname "localhost" is not configured under your images in your next.config.js".

标签: javascript node.js reactjs typescript next.js


【解决方案1】:

问题解决了!我只是在next.config.js的域中添加“localhost”

【讨论】:

    【解决方案2】:

    你可以制作一个loader函数来从它的目的地加载图片,然后在image标签的loader属性中调用loader函数。

    这是加载器函数的语法(取自next.js loader function documentation):

    import Image from 'next/image'
    
    const myLoader = ({ src, width, quality }) => {
      return `https://example.com/${src}?w=${width}&q=${quality || 75}`
    }
    
    const MyImage = (props) => {
      return (
        <Image
          loader={myLoader}
          src="me.png"
          alt="Picture of the author"
          width={500}
          height={500}
        />
      )
    }
    

    也可以看这里的解决方案,尤其是Taskmaster的示例加载器函数代码:

    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`

    【讨论】:

    • 我在哪里做这个功能?
    • 您应该能够在与图像组件相同的文件中创建函数。 loader 函数会覆盖 next.config.js 的 image 部分中的任何默认加载器(如果存在)。请参阅 next.js 图像加载器函数文档中的示例:nextjs.org/docs/api-reference/next/image
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多