【问题标题】:Could not get image file from API URL in nodejs无法从 nodejs 中的 API URL 获取图像文件
【发布时间】:2020-03-19 17:44:48
【问题描述】:
const headers = new Headers();

headers.set(
  "Authorization",
   "Basic " + base64.encode(username + ":" + password)
);

fetch(url, { method: "GET", headers: headers })
  .then(res => {
    console.log("res", res.statusCode);
  });

res.send("success");

我正在尝试使用 API URL 从 url 获取 jpeg 图像文件。当我尝试保存文件时,出现以下错误:

(node:18636) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at [API url] reason: Unexpected token � in JSON at position 0

使用 Advance Rest Client chrome Web 应用程序显示图像时,该 URL 有效。但是使用上面的代码它在 node.js 中不起作用。有人可以帮我解决这个问题吗?那将不胜感激。

【问题讨论】:

    标签: javascript node.js express node-fetch


    【解决方案1】:

    你使用的 res.statusCode 是错误的,你应该使用 res。相反,下面是工作代码。您可以根据需要对其进行修改。

    const fetch = require('node-fetch');
        const fs =    require('fs')
        fetch('https://homepages.cae.wisc.edu/~ece533/images/airplane.png')
          .then(res => {
            if(res.status==200) {
              let contentType =res.headers.get('content-type')
              if(contentType=='image/png') {
                let stream  = fs.createWriteStream('./test.png')
                 res.body.pipe(stream)
              }
             }
          })
    

    ;

    【讨论】:

    • 如果您的服务返回字节格式,则将其转换为 base64 字符串并首先通过 sub stract 加载直到;
    猜你喜欢
    • 2021-10-13
    • 2018-08-24
    • 2015-10-02
    • 2017-01-29
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多