首页 > 解决方案 > 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。

我试过了:

图像在输出路径 /.next/static/images/ 内正确加载

标签: reactjsstaticnext.js

解决方案


您正在使用自定义 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 示例。


推荐阅读