在我的 Next.js 项目中,我有一个管理部分,管理员可以在其中上传产品图片。图片保存在“[项目文件夹]/public/images”路径下,图片名称保存在数据库中。
我使用以下代码在网站上显示图像:
const PATH = process.env.NEXT_PUBLIC_IMAGES_PATH; // /images
const img = image; // The name of the image that is read from the database
<div>
<Image src={`${PATH}/${img}`} alt="" fill />
</div>
但是,在构建项目并上传新图像后,我收到以下错误消息:
所请求的资源不是 /images/1684186884098-567686341.png 收到的 text/html 的有效图像;字符集=utf-8
但是经过查找并结合多种方法后,我终于解决了更改包含这些部分的问题
我尝试了多种方法来解决这个问题,我所做的更改包括以下部分:
添加了 server.js 文件
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use("/images", express.static(__dirname + "/public/images"));
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
将以下代码添加到next.config.js:
const nextConfig = {
reactStrictMode: true,
images: {
domains: ["mydomain.com"],
},
};
修改组件代码如下:
const PATH = process.env.NEXT_PUBLIC_IMAGES_PATH; // /images
const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN; // mydomain.com
const img = image; // The name of the image that is read from the database
<div>
<Image src={`${DOMAIN}/${PATH}/${img}`} alt="" fill />
</div>
作为Next.js的初学者,我不确定这是否是解决问题的正确方法,我想知道是否有更好的方法。
我在 Render.com 上的静态 NextJS 网站上遇到了类似的问题。我读过有关 NextJS 优化图像的内容,并认为一切都很好,但图像是以文本/html 的形式获取的。我也跑了:
npm i sharp
按照NextJS安装sharp包进行图像优化,但没有帮助。
我终于看到了 Tushar Shahi 的这篇post,他们解释说,运行下一次导出时,不支持图像优化。
我必须将未优化的图像添加到我的 next.config.mjs 文件中,这解决了我的问题:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
reactStrictMode: true,
images: {
unoptimized: true,
}
};
export default nextConfig;
我的图像现在作为图像提供。
不确定这是否对动态图像有帮助。您可能还想查看此信息。 图像优化