【问题标题】:Node Fastify - serve images located in upload folderNode Fastify - 提供位于上传文件夹中的图像
【发布时间】:2021-11-02 09:17:22
【问题描述】:

当我们导航到

时,使文件/图像可供访问

localhost:8000/properties/files/[image name]

localhost:8000/properties/files/1635843023660-profile.jpg

文件结构

node_modules
src/
uploads/
    1635843023660-profile.jpg
    1635843023668-home.jpg
...
.env
package.json

index.js

import Fastify from "fastify";
import FastifyStatic from "fastify-static";
import path from "path";
import { propertiesRoutes } from "./routes/properties.js";
...
export const fastify = await Fastify({ logger: process.env.LOGGER || true });

const __dirname = path.resolve(path.dirname(""));
fastify.register(FastifyStatic, {
  root: path.join(__dirname, "uploads"),
});
fastify.register(propertiesRoutes, { prefix: "/properties" });
...

routes/properties.js

export const propertiesRoutes = function (fastify, opts, done) {
  ...
  fastify.get("/images/:name", (req, res) => {
    res.sendFile(process.cwd() + "/uploads/" + req.params.name);
  });
  done();
};

现在我得到了

{"message":"Route GET:/properties/images/1635843023660-profile.jpg 不是 找到","错误":"未找到","statusCode":404}

【问题讨论】:

    标签: javascript node.js fastify


    【解决方案1】:

    当您没有在 FastifyStatic 配置中指定 prefix 时,将使用默认的 /。因此,为了访问您的静态文件,您需要将请求路径从 /properties/images/<your-img.jpg> 更改为 /images/<your-img.jpg>

    或者,您可以使用 public 之类的自定义前缀,就像他们在 documentation 中所做的那样:

    fastify.register(require('fastify-static'), {
      root: path.join(__dirname, 'uploads'),
      prefix: '/public/',
    })
    

    然后用/public/images/<your-img.jpg>请求它。

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多