在 /public/ 我有一个名为 /public/cms_images 的文件夹。
每当用户使用我们创建的管理门户上传图像时,cms_images 就会被填充(与 next.js 项目、其 asp.net 分开,只是将图像放入我的 next.js 项目的文件夹中)在 /pageThatUsesImage.js 上,如果我构建应用程序并为其提供服务(下一个构建 && 下一个启动),页面将工作并引用图像
但是当添加新图像时,图像会抛出 404
我通过客户端 API 调用引用图像的文件名 + 文件类型。
<img
src={`/cms_images/` + dataFromPageAPI.imageFileName}
/>
是否有任何解决办法可以让动态添加的图像在运行时显示?
https://nextjs.org/docs/pages/api-reference/components/image)。我的后端在“/api”上运行,但需要使用完整的 url 引用源。以下解决了它:
// image.component.tsx
import { default as NextImage, ImageProps } from "next/image";
export const backendUrl = (src: string) => {
const isServerSided = typeof window === "undefined";
return isServerSided
? `${process.env.NEXT_PUBLIC_URL_SELF}/api${src}`
: `${window.origin}/api${src}`;
};
export const Image = (props: ImageProps) => {
if (typeof props.src !== "string") {
return;
}
return <NextImage {...props} src={backendUrl(props.src)} />;
};
您需要在环境变量中定义“NEXT_PUBLIC_URL_SELF”https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables
这里的好处是: