使用gaxios(或axios)的管道请求



目前,我正在执行将请求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库这个技巧可能吗?我原以为在请求中设置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

然后使用指定了Readable类型的请求,并将responseType设置为"流">

// 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客户端库中使用。它基于稳定的节点获取。它与开箱即用的TypeScript定义配合使用。我从弃用的请求和普通节点获取库切换到了它。

我想如果您将responseType提供为stream并使用res.data,您将获得一个流,您可以像以下一样进行管道传输

const {request} = require("gaxios");
const fs = require("fs");
const {createGzip} = require("zlib");
const gzip = createGzip();
(async () => {
const res = await request({
"url": "https://www.googleapis.com/discovery/v1/apis/",
"responseType": "stream"
});
const fileStream = fs.createWriteStream("./input.json.gz");
res.data.pipe(gzip).pipe(fileStream);
})();

看起来您基本上是在尝试将请求从express服务器转发到客户端。这对我有效。

import { request } from "gaxios";
const express = require("express");
const app = express();
const port = 3000;
app.get("/", async (req: any, res: any) => {
const readableA = (await request({
url: "https://google.com",
responseType: "stream",
})) as any;
console.log(req, readableA.data);
const readableB = await readableA.data.pipe(res);
console.log(res, readableB);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

我想,来自A的更复杂的响应将需要更多的管道技巧。但是,您可能只需要直接与express的响应对象交互并设置适当的字段。

最新更新