NodeJS 在自定义API中返回随机图像时出现问题

6rvt4ljy  于 2023-02-03  发布在  Node.js
关注(0)|答案(2)|浏览(112)

使用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项目,不知道在这种情况下会出现什么问题。

fbcarpbf

fbcarpbf1#

fetch是一个承诺,因此您需要等待fetch并返回blob响应

app.get("/media/bigfootjinx", async (req, res, next) => {
    let file = Math.floor(Math.random()*catarray.length)
        let fileurl = catarray[file]
        let response = await fetch(fileurl)
        let fileimg = await response.blob()
    let img = await blobToBase64(fileimg);
    res.writeHead(200, {
        'Content-Type': 'image/png',
        'Content-Length': img.length
    });
    res.end(img); 
});

从blob到base64的转换函数:

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}
xqkwcwgp

xqkwcwgp2#

以下代码行导致该错误:

let img = Buffer.from(fileimg, 'base64');
let fileimg = fetch(fileurl)

fetch()函数返回一个Promise<Buffer>,你只需 * 等待 * 获取结果,你可以这样做:

let fileimg = await fetch(fileurl)
let img = Buffer.from(fileimg, 'base64');

**注意:**get端点的回调函数必须是异步的:

app.get("/media/bigfootjinx", async (req, res, next) => {

相关问题