如何通过Node.js Express应用程序调用API获取PNG格式图片?

3

我需要能够通过Node.js Express应用程序从API端点返回png图像。

当尝试返回图像/ SVG文件时,它按预期返回并呈现。但是当我尝试使用png文件时,我会得到一些编码不佳的文本,如下所示:

Original Answer翻译成"最初的回答"

�PNG  IHDR\���IDATx�]�U��:Ӂ�.��*��������]�{�A�A�(�� �\���1���   �� A@6���$�(�CXX|d��IUu�dz�渤�g��u�����sO�1��g��W�����~fv��+�TL�z�qןc��e��;��{��狿

这是我现在的代码:

const express = require('express')
const request = require('request-promise')
const port = 3000
const exphbs = require('express-handlebars')
const app = express()

const options = {
  method: 'GET',
  uri: 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
  headers: {
    'Accept': 'image/png',
    'Content-Type': 'image/png'
  }
}



app.get('/', (request, response) => {
    test(response)
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }
  console.log(`server is listening on ${port}`)
})


function test(resp){
 return request(options).then((data)=>{
    resp.header('Content-Type', options.headers['Content-Type']).send(data);
  }).catch((err) => {
      console.log(err)
      data.render('error')
})
}

1
res.header('Content-Type', options.headers['Content-Type']).send(data); - Lawrence Cherone
浏览器仍然使用响应中设置的内容类型加载上述字符串。 - Ray
1
有点奇怪,还在研究中,如果你只是使用管道 request("http://...").pipe(resp); 它可以工作。 - Lawrence Cherone
1
旁注:data.render('error')是错误的,因为数据不会被设置。 - Lawrence Cherone
@LawrenceCherone 谢谢,我会进行管道传输:)。我认为尝试以错误编码(也许?)将图像读取为字符串导致图像损坏。我下载了损坏的 PNG 文件并与原始文件进行比较,十六进制数据相似但某些位置上有一些额外值。 - Ray
酷,是的,不确定发生了什么哈哈,它在codesandbox上间歇性地工作,我以为Buffer.from是一个解决方法,但那也停止工作了,我认为request-promise可能会做些什么,尝试了普通请求(回调),但不行,没有其他可尝试的方法,所以放弃了,抱歉:( - Lawrence Cherone
1个回答

1

这里有解决我的问题的方法。感谢 @LawrenceCherone。

const express = require('express')
const request = require('request-promise')
const port = 3000
const exphbs = require('express-handlebars')
const app = express()

const options = {
  method: 'GET',
  uri: 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
  headers: {
    'Accept': 'image/png'
  }
}

app.get('/', (request, response) => {
    response.setHeader('Content-Type', 'image/png')
    makeRequest(response)
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }
  console.log(`server is listening on ${port}`)
})


function makeRequest(resp){
    request(options.uri, options).pipe(resp)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接