在本地主机上设置 next.config.js remotePatterns 以从本地 API 获取图像

Som*_*ice 4 reactjs next.js

你好,我正在尝试制作一个随机图像 API,因此当我访问页面 http://localhost:3000/random-img 时,我会得到一个随机的新图像。

我的目标是能够像这样使用 url<Image src="http//localhost:3000/random-img alt="something" fill>

不幸的是,我在尝试配置本地主机后收到错误

Error: Invalid src prop (http://localhost:3000/random-img) on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
Run Code Online (Sandbox Code Playgroud)

这是我的配置文件,有一个有效的示例,然后这个本地主机就是https://nextjs.org/docs/api-reference/next/image上的文档中描述的方式

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "placeimg.com",
        port: "",
        pathname: "/720/480/**",
      },
      {
        protocol: "http",
        hostname: "localhost",
        port: "3000",
        pathname: "/**",
      },
    ],
  },
};
 

Run Code Online (Sandbox Code Playgroud)

这是“http://localhost:3000/random-img


function randomimg({ img }) {
  img = `img/${img}`;

  return (
    <>
      <img src={img} alt='lol' />


    </>
  );
}

export async function getServerSideProps() {
  const getImg = await fetch("http://localhost:3000/api/");
  const imgName = await getImg.json();

  return {
    props: {
      img: imgName.image,
    },
  };
}

export default randomimg;

Run Code Online (Sandbox Code Playgroud)

这是pages/api/中的api

export default function handler(req, res) {
  const fs = require("fs");

  const files = fs.readdirSync("public/img");

  const len = files.length;
  let number = Math.floor(Math.random() * len);

  res.status(200).json({ image: files[number] });
}
Run Code Online (Sandbox Code Playgroud)

Dev*_*B2F 5

  1. 将以下内容添加到 next.config.js 文件中:

    const nextConfig = {
       reactStrictMode: true,
       images: {
           domains: ['127.0.0.1'],
       },
    };
    
    module.exports = nextConfig;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在图像组件中使用这样的 url:

    import Image from 'next/image';
    const ImageComponent: React.FC = () => (
        <div>
            <Image src={'http://127.0.0.1:8000' + '/path/toImage.png'} alt={'alt'} width={28} height={28} />
        </div>
    );
    
    Run Code Online (Sandbox Code Playgroud)
  3. 重新启动 nextjs 服务器以使更改生效