// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项: // `keepAlive` 默认没有启用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }),
axios.get('/user/12345').catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx // 渣翻:当请求发出后,服务器返回了一个响应 // 而且响应的状态码(status code)不是2xx范围内 console.log(error.response.data) console.log(error.response.status) console.log(error.response.headers) } elseif (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js // 渣翻:请求发出但是没接收到响应 // `error.request`在浏览器端是发送请求的xhr实例,在node是http.ClientRequest实例 console.log(error.request) } else { // Something happened in setting up the request that triggered an Error // 在设置请求时发生了错误,在这里会被捕捉到 console.log('Error', error.message) } console.log(error.config) })
可用使用 validateStatus 配置选项定义一个自定义 HTTP 状态码错误范围。
1 2 3 4 5 6 7
axios.get('/user/12345', { validateStatus: function (status) { // Reject only if the status code is greater than or equal to 500 // 渣翻:当状态码大于等于500时才触发reject return status < 500 }, })