javascript - 使用 gaxios(或 axios)管道请求

标签 javascript node.js axios node-streams

目前我正在执行管道请求 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/

相关文章:

node.js - nodejs框架最好的框架是什么以及区别

React 中 Axios 调用时 API 中的 PHP-Session 发生变化

node.js - axios 获取请求错误 : Request failed with status code 504

javascript - 对于 IE 中的 ajax 内容,onload 触发过早

javascript - Node websocket 服务器 TypeError : Argument must be a string

javascript - 语法错误 : let is a reserved identifier on firefox

javascript - 将参数传递给node.js中的路由

javascript - React - Axios promise 未定义的未决值

javascript - 如果在输入框中输入特定值,则使用 javascript 显示一条消息

javascript - 具有固定第一个元素的水平 <ul>