javascript - Node Fastify - 提供位于上传文件夹中的图像
问题描述
当我们导航到时,使文件/图像可供访问
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" });
...
路线/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 not found","error":"Not Found","statusCode":404}
解决方案
如果未prefix
在FastifyStatic
配置中指定 a,则将使用默认值/
。因此,为了访问您的静态文件,您需要将请求路径从 更改/properties/images/<your-img.jpg>
为/images/<your-img.jpg>
.
public
或者,您可以像在文档中那样使用自定义前缀:
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'uploads'),
prefix: '/public/',
})
然后用/public/images/<your-img.jpg>
.
推荐阅读
- javascript - 无法读取 null 的属性“addEventListener”,有没有更好的方法来防止这种情况
- graphql - 如何使用带有特定参数的 Nexus 的 Prisma 插件 crud
- list - 如何在不手动复制和粘贴的情况下循环遍历 python 生成的列表?
- python - 在 Python 中查询输入是 int 还是 str
- php - 使用 ajax 向 Textarea 显示值不起作用
- reactjs - 反应生命周期方法 - 过滤的正确方法
- r - 使用 stringdist_join 通过多列连接
- autodesk-forge - Autodesk forge Viewer - C# - 从 Revit 文件中获取属性
- python - 计算丢帧率的问题
- excel - 我怎样才能点击一个按钮“onclick”..使用xml