我有一个 API 试图向 API 发出 HTTP 请求,该 API 将流式传输和图像传回给我,然后将该图像流式传输回向我发出请求的客户端,或者等到图像流式传输到我并立即发送。
我正在使用 Express 和请求 promise 。
这是我的代码的简化版本。
const express = require('express');
const router = express.Router();
const request = require('request-promise');
const imgFunc = async () => {
try {
const response = await request.get({
method: 'GET',
uri: `http://localhost:8080`,
});
return response;
} catch(err) {
console.log(err);
}
};
router.get('/', async function(req, res, next) {
try {
const response = await imgFunc();
return res.send(response);
} catch (err) {
console.log(err);
}
});
module.exports = router;
我取回的图像正是我假设的二进制数据,我不知道我是否需要在请求- promise 级别做一些事情以使其正确,或者我何时将其发送回客户端。
我在 localhost:8080 上运行的服务器模拟了我将在完成所有操作后访问的实际服务器。
最佳答案
您可以直接通过管道传输流,而不是使用 request-promise
。
const express = require('express');
const router = express.Router();
const https = require('https');
router.get('/', function(req, res) {
const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=PG&f=1';
const request = https.get(url, function(response) {
const contentType = response.headers['content-type'];
console.log(contentType);
res.setHeader('Content-Type', contentType);
response.pipe(res);
});
request.on('error', function(e){
console.error(e);
});
});
module.exports = router;
或者使用request-promise
所基于的request
库:
const express = require('express');
const router = express.Router();
const request = require('request');
router.get('/', function(req, res) {
const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=PG&f=1';
request.get(url).pipe(res);
});
module.exports = router;
关于node.js - 将响应流式传输到 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145738/