使用Express和Node JS,我正在做一个返回随机猫图像的东西。但是,我在下面的代码中遇到了一些问题,正在寻找解决方案。
app.get("/media/funnycats", (req, res, next) => {
let file = Math.floor(Math.random()*catarray.length)
let fileurl = catarray[file]
let fileimg = fetch(fileurl)
let img = Buffer.from(fileimg, 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
});
我的目标是得到一个随机的猫图像回来,他们都在pngs和链接到cdn。错误我不断得到下面列出,我有麻烦解决它:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Promise
at Function.from (buffer.js:330:9)
at /home/runner/api/index.js:21:22
at Layer.handle [as handle_request] (/home/runner/api/node_modules/express/lib/router/layer.js:95:5)
at next (/home/runner/api/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/runner/api/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/runner/api/node_modules/express/lib/router/layer.js:95:5)
at /home/runner/api/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/runner/api/node_modules/express/lib/router/index.js:335:12)
at next (/home/runner/api/node_modules/express/lib/router/index.js:275:10)
at expressInit (/home/runner/api/node_modules/express/lib/middleware/init.js:40:5)
我使用的是node.js项目,不知道在这种情况下会出现什么问题。
2条答案
按热度按时间fbcarpbf1#
fetch是一个承诺,因此您需要等待fetch并返回blob响应
从blob到base64的转换函数:
xqkwcwgp2#
以下代码行导致该错误:
fetch()
函数返回一个Promise<Buffer>
,你只需 * 等待 * 获取结果,你可以这样做:**注意:**get端点的回调函数必须是异步的: