管道请求时如何对响应状态代码做出反应

时间:2020-09-25 21:30:37

标签: javascript node.js pipe response

我有一个简单的http代理,可以读取传入的请求,添加一些标头(cookie),将其发送到服务器,并将响应通过管道传递到原始客户端。

const express = require("express");
const request = require("request");
const axios = require("axios");
...
app.use("/", function (req, res) {

let url = "https://myurl.example.com" + req.url;
let query = Object.assign(req.query);

let newRequest = request({ qs: query, uri: url });
newRequest.headers.referer = "https://myurl.example.com";
newRequest.headers.cookie = cookies;
let response = req.pipe(newRequest);
response
  .on("response", (onresponse) => {
    if (onresponse.statusCode !== 200) {
      console.log(onresponse.statusCode);
      getCookies(); // sets the cookies global variable
    } 
  })
  .pipe(res);
});

现在,我想对statusCode做出反应,如果它是401,请刷新cookie(通过调用getCookies()),然后在同一运行中再次发送请求并将正确的响应通过管道发送回客户端(因此客户不了解401)。我该怎么办?

0 个答案:

没有答案