reactjs - NextJS 图像未加载
问题描述
在我的根项目中,我有一个 /public 持有人设置了“home.jpg”和“home-placeholder.jpg”图像文件。
在我的 /pages/index.js 文件中,我有一个包含两个图像的组件:
function Page() {
return (
<>
<Head title="Home" />
<Home>
<Right
alt="home-image"
image="./home.jpg"
placeholder="./home-placeholder.jpg"
/>
</Home>
</>
);
}
我无法让这些图像显示在我的开发服务器中,我总是得到:无法获取 /home.jpg。
我试过了:
- 使用下一个图像并导入图像
- 在我的生产服务器上构建和部署
- 将公用文件夹的名称更改为 /static/
图像在输出路径 /.next/static/images/ 内正确加载
解决方案
您正在使用自定义 Express 服务器,但缺少 Next app requestHandler:
import * as Routes from "~/src/routes";
import express from "express";
import next from "next";
const dev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 8000;
const app = next({ dev, quiet: false });
const handle = app.getRequestHandler(); // <----
app.prepare().then(() => {
const server = express();
server.get("/", async (req, res) => {
return await Routes.signIn(req, res, app);
});
server.all("*", (req, res) => { // <----
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`Server running on http://localhost:${port}`);
});
});
查看Next.js的这个Custom Express Server 示例。
推荐阅读
- java - 保存的 ImageView 保存为 byte[] 后没有出现
- javascript - 如何在 Vue.js 中调整文本字段的响应性
- jquery - 返回响应数据不适用于 html
- python - Nibabel 库中的 get_data 和 get_fdata 有什么区别?
- python - Kivy.Clock 的“.cancel()”函数不起作用?
- angular - Angular http请求在chrome中返回null,但在firefox中有效
- sql - 蜂巢:如何通过正则表达式选择除列名“cust_id”之外的所有列
- javascript - touchmove 事件意外触发 onload
- database - 在微服务架构中扩展数据库
- laravel - laravel 服务使用模型和服务