【问题标题】:NextJS images not loadingNextJS 图像未加载
【发布时间】:2020-10-07 11:23:06
【问题描述】:

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

我无法让这些图像显示在我的开发服务器中,我总是得到:Cannot GET /home.jpg。

我试过了:

  • 使用下一个图像并导入图像
  • 在我的生产服务器上构建和部署
  • 将公用文件夹的名称更改为 /static/

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

【问题讨论】:

  • 您是否尝试在运行开发服务器之前删除.next 文件夹?
  • @Hangindev 谢谢,我试过了,但没有运气。图像路径是“localhost:8000/home-placeholder.jpg”而不是 .next 文件夹输出。如果您想查看 repo,请点击此处:github.com/sanderdebr/sleepdiary
  • 我看到您使用的是自定义服务器。我尝试使用next dev 启动开发服务器,并且图像已正确加载。所以你可能需要在你的自定义服务器中做一些设置来提供静态文件,我猜。

标签: reactjs static next.js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 2021-03-31
    • 2022-08-21
    • 2022-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2021-10-29
    相关资源
    最近更新 更多