當我們導航到時,使檔案/影像可供訪問
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
索引.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}
uj5u.com熱心網友回復:
當未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>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/345386.html
標籤:javascript 节点.js 固定
