如何在 vercel 上托管的 express js 中加载图像
How to load images in express js hosted on vercel
我正在尝试使用 express js 制作一个 GitHub 横幅生成器,我的代码在本地运行良好,但是当我尝试在 Vercel 上托管它时,所有图像文件都丢失了,我得到 no such file or directory found
错误。
app.get('/api',async(req,res)=>{
const title = req.query.title || "Github Banner Generator"
const subTitle = req.query.subtitle || ""
const theme = req.query.theme || "default"
const _theme = require(`./themes/${theme}/${theme}.json`)
const image = await loadImage(fs.readFileSync('themes/default/image1.png'))
const img = await new Canvas(1280, 520)
.printImage(image,0,0)
.setColor(_theme.primaryColor)
.setTextFont('bold 60px Serif')
.setTextAlign('center')
.printText(title,1280/2,520/2)
.setTextFont('20px Serif')
.setTextAlign('center')
.printText(subTitle,1280/2,(520/2)+60)
.toBuffer();
res.set({'Content-Type':'image/png'})
res.send(img)
})
我认为图片路径不对,因为你没有使用绝对路径。您应该阅读有关 the difference between ./
and __dirname
in NodeJS.
的更多信息
我的解决方案是使用 __dirname + (the file location depending on the current file folder)
const image = await loadImage(fs.readFileSync(__dirname
+ '/themes/default/image1.png'));
在这里,我假设您的项目结构看起来像这样...
/package.json
/index.js (contains the code)
/themes/default/image1.png
我正在尝试使用 express js 制作一个 GitHub 横幅生成器,我的代码在本地运行良好,但是当我尝试在 Vercel 上托管它时,所有图像文件都丢失了,我得到 no such file or directory found
错误。
app.get('/api',async(req,res)=>{
const title = req.query.title || "Github Banner Generator"
const subTitle = req.query.subtitle || ""
const theme = req.query.theme || "default"
const _theme = require(`./themes/${theme}/${theme}.json`)
const image = await loadImage(fs.readFileSync('themes/default/image1.png'))
const img = await new Canvas(1280, 520)
.printImage(image,0,0)
.setColor(_theme.primaryColor)
.setTextFont('bold 60px Serif')
.setTextAlign('center')
.printText(title,1280/2,520/2)
.setTextFont('20px Serif')
.setTextAlign('center')
.printText(subTitle,1280/2,(520/2)+60)
.toBuffer();
res.set({'Content-Type':'image/png'})
res.send(img)
})
我认为图片路径不对,因为你没有使用绝对路径。您应该阅读有关 the difference between ./
and __dirname
in NodeJS.
我的解决方案是使用 __dirname + (the file location depending on the current file folder)
const image = await loadImage(fs.readFileSync(__dirname
+ '/themes/default/image1.png'));
在这里,我假设您的项目结构看起来像这样...
/package.json
/index.js (contains the code)
/themes/default/image1.png