NextJS图片未加载

时间:2020-06-17 15:16:42

标签: reactjs static next.js

在我的根项目中,我有一个/ 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/

1 个答案:

答案 0 :(得分:1)

您正在使用自定义Express Server,但是缺少下一个应用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 example