Axios 代理配置导致错误请求

问题描述 投票:0回答:1

我正在尝试从 NodeJS 应用程序向粒子云发送请求。 我正在使用 Axios 发出 PUT 请求。应用程序通过同样配置的代理服务器发送请求。

// axios proxy - not working
axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
proxy: {host: <proxy_ip>, protocol:'http', port:<port_no>},
headers: {
    authorization: "Bearer <access_token>"
}
}).then((response) => {
    console.log("Success", response.data);
}).catch((error) => {
   console.log("Failed", error);
});

错误消息:请求失败,状态代码为 400

当我发送此请求时,我从粒子云收到 400 Bad Request 响应。 但是当我使用NodeJS的请求模块发送相同的请求时,请求成功了。

var options = {
   method: 'PUT',
   url: 'https://api.particle.io/v1/devices/<device_id>/ping',
   proxy: {hostname: <proxy_ip>, protocol:'http', port:<port_no>},
   headers: 
   { 
       authorization: 'Bearer <access_token>'
   },
   form: false
};
request(options, function (error, response, body) {
   if (error) throw new Error(error);
   console.log(response);
});

响应:正文:'{“online”:false,“ok”:true}'

当应用程序部署在开放网络上并且在没有代理配置的情况下使用 axios 时,该请求也有效。

// axios without proxy - working
axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
    headers: {
        authorization: "Bearer <access_token>"
    }
}).then((response) => {
    console.log("Success", response.data);
}).catch((error) => {
    console.log("Failed", error);
});

问题:

  1. 为什么配置代理后axios请求失败?
  2. 这是 Axios 固有的问题吗?

问候。

node.js axios particle-photon
1个回答
7
投票

axios 本身有一个 bug 尚未修复。

为了解决这个问题,可以使用 https-proxy-agent 代替 axios proxy。

const { HttpsProxyAgent } = require('https-proxy-agent')

axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
    headers: {
        authorization: "Bearer <access_token>"
    }, 
    proxy: false,
    httpsAgent: new HttpsProxyAgent('http://proxy_domain:port')
}).then((response) => {
    console.log("Success", response.data);
}).catch((error) => {
    console.log("Failed", error);
});
© www.soinside.com 2019 - 2024. All rights reserved.