前端向服务端发起一个请求 服务端如何请求另一个接口并把其返回的流数据 同样以流发送给前端?
服务端可以使用类似于axios、fetch等HTTP库向另一个接口发起请求,并通过流式处理方式将返回的数据流转发给前端。以下是一个示例代码:
const axios = require('axios');
const http = require('http');
const server = http.createServer((req, res) => {
// 向另一个接口发起请求
axios({
url: 'http://example.com/api',
method: 'GET',
responseType: 'stream'
}).then(response => {
// 将返回的数据流转发给前端
response.data.pipe(res);
}).catch(error => {
console.error(error);
res.statusCode = 500;
res.end();
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
在上述代码中,我们创建了一个HTTP服务器,并在请求处理函数中向另一个接口发起了一个GET请求,设定responseType为stream以获取数据流,然后将返回的数据流通过pipe方法转发给前端。如果请求出错,我们会将响应码设为500并结束响应。
原文地址: https://www.cveoy.top/t/topic/GkD 著作权归作者所有。请勿转载和采集!