我正在嘗試使用 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)
})

uj5u.com熱心網友回復:
我認為影像路徑不正確,因為您沒有使用絕對路徑。你應該閱讀更多關于NodeJS和之間的區別./__dirname。
我的解決方案是使用__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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486070.html
