目前我正在执行管道请求 req
的技巧到目标 url,并将响应返回到 res
,像这样:
const request = require('request');
const url = 'http://some.url.com' + req.originalUrl;
const destination = request(url);
// pipe req to destination...
const readableA = req.pipe(destination);
readableA.on('end', function () {
// do optional stuff on end
});
// pipe response to res...
const readableB = readableA.pipe(res);
readableB.on('end', function () {
// do optional stuff on end
});
由于request
现在已正式弃用 (boo hoo),这个技巧是否可以使用 gaxios library ?我以为设置responseType: 'stream'
在请求上会做与上面类似的事情,但它似乎不起作用。类似地,可以在以下情况下使用 gaxios:
request
.get('https://some.data.com')
.on('error', function(err) {
console.log(err);
})
.pipe(unzipper.Parse())
.on('entry', myEntryHandlerFunction);
最佳答案
安装gaxios:npm install gaxios
然后将 request 与 一起使用可读 指定类型和 响应类型 设置为 '流' .
// script.ts
import { request } from 'gaxios';
(await(request<Readable>({
url: 'https://some.data.com',
responseType: 'stream'
}))
.data)
.on('error', function(err) {
console.log(err);
})
.pipe(unzipper.Parse())
.on('entry', myEntryHandlerFunction);
// first-example.ts
import { request } from 'gaxios';
// pipe req to destination...
const readableA = (await request<Readable>({
url: 'http://some.url.com',
method: 'POST',
data: req, // suppose `req` is a readable stream
responseType: 'stream'
})).data;
readableA.on('end', function () {
// do optional stuff on end
});
// pipe response to res...
const readableB = readableA.pipe(res);
readableB.on('end', function () {
// do optional stuff on end
});
Gaxios 是一个稳定的工具,用于官方的 Google API 客户端库。它基于稳定的 Node 获取。它与开箱即用的 TypeScript 定义一起使用。我从弃用的请求和普通的 node-fetch 库切换到它。
关于javascript - 使用 gaxios(或 axios)管道请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532289/