gpt4 book ai didi

node.js - 如何通过 Nodejs Express 应用程序调用 API 获取 png 图像

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:27 25 4
gpt4 key购买 nike

我需要能够通过 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)
}

关于node.js - 如何通过 Nodejs Express 应用程序调用 API 获取 png 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com