首页 > 解决方案 > 如何通过 nodejs express 应用程序调用 API 获取 png 图像

问题描述

我需要能够通过 nodejs express 应用程序从 API 端点返回 png 图像。

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

�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')
})
}

标签: node.jsrestexpressrequestmime-types

解决方案


在这里解决我的问题。感谢@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)
}

推荐阅读