[axios]带有代理的 Axios 请求无法正确重定向

2024-08-22 794 views
0
 概括

使用代理的 Axios 请求无法正确重定向,如下所述:

请求:

const axios = require('axios')

axios.get('http://testapi.testdomain.com/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10', {
  proxy: {
    host: '127.0.0.1',
    port: 1080
  }
})
.then((response) => {
  console.log(response)
})
.catch((err) => {
  console.log(err)
})

响应:

$ node axios_promise.js
{ Error: connect ECONNREFUSED 127.0.0.1:80
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.17.1' },
     method: 'get',
     proxy: { host: '127.0.0.1', port: 1080 },
     url: 'http://testapi.testdomain.com/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10',
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     domain: null,
     _events:
      { response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { maxRedirects: 21,
        protocol: 'http:',
        hostname: '127.0.0.1',
        port: null,
        path: '/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
        method: 'GET',
        headers: [Object],
        agent: undefined,
        auth: null,
        host: '127.0.0.1',
        pathname: '/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc',
        search: '?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
        slashes: true,
        hash: null,
        query: 'page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
        href: 'http://127.0.0.1/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut' },
     _redirectCount: 1,
     _bufferedWrites: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'GET /api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.17.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://127.0.0.1/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
     _isRedirect: true },
  response: undefined }

请注意顶部的响应的错误部分:

{ Error: connect ECONNREFUSED 127.0.0.1:80
    at Object.exports._errnoException (util.js:1022:11)

底部的响应部分:

     _currentUrl: 'http://127.0.0.1/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut',
     _isRedirect: true },

我得到的是http://127.0.0.1/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut

我期望的是 http://testapi.testdomain.com/api/articles/personal/01d76a9844ae4a919f02ddedf11a6fcc?page=2&size=10&uc_param_str=dnvebichntwidsudsvpflameefut

 语境
  • axios版本: v0.17.1
  • 环境: node vv8.1.4,windows 10

回答

1

和 @kidlj 有同样的问题,axios 在使用代理时似乎无法正确重定向

3

这里也有同样的问题,下面是用于重现的最小化代码

var axios = require('axios');
var http = require('http');
var url = require('url');

var str = 'test response', proxyStr = ' through proxy'

var server = http.createServer(function (req, res) {
  var parsed = url.parse(req.url);

  if (parsed.pathname === '/one') {
    res.setHeader('Location', '/two');
    res.statusCode = 302;
    res.end();
  } else {
    res.end(str);
  }
}).listen(4444, function () {

  var proxy = http.createServer(function (request, response) {
    var parsed = url.parse(request.url);
    var opts = {
      hostname: parsed.hostname,
      port: parsed.port,
      path: parsed.path
    };

    http.get(opts, function (res) {
      var body = '';
      res.on('data', function (data) {
        body += data;
      });
      res.on('end', function () {
        if (res.headers.location) {
          response.setHeader('Location', res.headers.location);
        }
        response.statusCode = res.statusCode;
        response.end(body + proxyStr);
      });
    });

  }).listen(4000, function () {

    axios.get('http://localhost:4444/one', {
      proxy: {
        host: 'localhost',
        port: 4000
      },
    }).then(function (res) {
      console.log(res.data); // should be "test response through proxy"
    });

  })
});
9

有任何更新吗?仍然遇到相同的错误。

2

仍然在这里

0

仍在等待修复

0

可以使用最新版本的 master 进行测试吗?

3

就我而言,这个问题仍然存在于最新版本的 master 中。与 OP 的问题相同。

9

进一步调查该问题后,我注意到协议在重定向到 https 时发生了变化。我的代理正在监听 http 端口,这导致了该问题。

redirection.protocol = 'http:';我已经通过添加beforeRedirect()函数(http.js源代码文件,在调用之前)手动修复了它setProxy()

图像

当然,这只是一个临时的解决方案,对我有用,但 @jasonsaayman 也许可以看看这个 :) 谢谢