我需要能够通过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')
})
}
答案 0 :(得分: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)
}