使用 NodeJS 和 Express 从本地主机获取图像会返回 404

Getting an image from localhost gives 404 with NodeJS and Express

我使用 multer 在 NodeJS Express 中实现了图像上传,当我尝试在浏览器中获取图像时出现此错误:

URL: http://localhost:5500/images/posts/5e2843e4efa65f188fc5552f.png
Cannot GET /images/posts/5e2843e4efa65f188fc5552f.png

我在控制台看到 404 所以我不明白为什么我看不到我的图像。

我是这样上传的:

postRouter.post(
    "/:id/uploadImg",
    multerConfig.single("image"),
    async (req, res) => {
        try {
            const fileName =
                req.params.id + path.extname(req.file.originalname);

            const newImageLocation = path.join(
                __dirname,
                "../../images/posts",
                fileName
            );

            await fs.writeFile(newImageLocation, req.file.buffer);

            req.body.image =
                req.protocol +
                "://" +
                req.get("host") +
                "/images/posts/" +
                fileName;

            const newPostImg = await Posts.findOneAndUpdate(
                { _id: req.params.id },
                {
                    $set: { image: req.body.image }
                }
            );

            newPostImg.save();

            res.send("Image URL updated");
        } catch (ex) {
            res.status(500).send({ Message: "Internal server error", err: ex });
        }
    }
);

在我的 server.js

server.use(express.static("./images"));

我可以上传,但无法看到它,也无法弄清楚是什么问题。

当您编写 server.use(express.static("./images")); 时,您告诉您的服务器从您应用程序的 ìmages 文件夹中搜索目录和文件 starting

因此您应该去 http://localhost:5500/posts/5e2843e4efa65f188fc5552f.png 搜索您上传的文件。假设在 server.use(express.static("./images"));.

之前没有其他匹配的路由

编辑:

如果您希望能够使用您已经在使用的路径,您应该像这样更改您的图像目录:

--images
  --images
    --posts
      -photo.png

并像这样更改您的 multer 代码保存文件的路径:

const newImageLocation = path.join(
                __dirname,
                "../../images/images/posts",
                fileName
            );