node.js - 如何通过 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')
})
}
解决方案
在这里解决我的问题。感谢@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)
}
推荐阅读
- android - Flutter/Dart - 我的 AndroidManifest.xml 中的这些红色字母是什么意思?他们是错误吗?
- c++ - c++ 分配器特征引用和 const_reference 缺失以及迭代器到 const 迭代器的转换
- ios - 嵌入框架中的 @Fetched 请求 SwiftUI 和实体
- c# - 在 XAML Xamarin 表单中将属性绑定到 RelativeLayout.XConstraint
- python - 为什么在 Python 的 print 函数中传递给关键字参数 end 的参数在以下上下文中不能按预期工作?
- java - 在 Gradle clean 之后,Android Studio 没有清理依赖项
- c# - 如何按子字符串值对列表项进行排序?C#
- gdb - 为什么在为 Cortex-M 中断处理程序生成的程序集中存在死循环?
- javascript - 更改挂载中添加的新变量时,视图不会更新
- php - 如何翻译csv中的特殊字符