axios-cookiejar-support与自定义https.Agent冲突报错求助
问题代码
const axios = require('axios') const https = require('https'); const axiosCookieJarSupport = require("axios-cookiejar-support"); const tough = require("tough-cookie"); const HEADERS = { 'Content-Type': 'application/json; odata.streaming=true; charset=utf-8', Accept: 'application/json; odata.metadata=none, text/plain', 'TM1-SessionContext': '----', 'User-Agent': '----' } this.http = axios.create({ headers: HEADERS, withCredentials: true, httpsAgent: new https.Agent({ rejectUnauthorized: false }) }) axiosCookieJarSupport.wrapper(this.http) this.http.defaults.jar = new tough.CookieJar() this.http.defaults.baseURL = this.baseUrl // Then other things but that doesn't matter
报错信息
Error: axios-cookiejar-support does not support for use with other http(s).Agent. at requestInterceptor (C:\node_modules\axios-cookiejar-support\dist\index.js:14:15) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async RestService.startSession (C:\main.js:109:29)
解决方案
问题原因
axios-cookiejar-support需要接管axios实例的http/https Agent来实现Cookie管理,提前自定义Agent会触发冲突检测,导致报错。
修改后的代码
const axios = require('axios') const axiosCookieJarSupport = require("axios-cookiejar-support"); const tough = require("tough-cookie"); const HEADERS = { 'Content-Type': 'application/json; odata.streaming=true; charset=utf-8', Accept: 'application/json; odata.metadata=none, text/plain', 'TM1-SessionContext': '----', 'User-Agent': '----' } // 创建axios实例时不指定自定义httpsAgent this.http = axios.create({ headers: HEADERS, withCredentials: true }) // 先包装实例以启用CookieJar支持 axiosCookieJarSupport.wrapper(this.http) this.http.defaults.jar = new tough.CookieJar() this.http.defaults.baseURL = this.baseUrl // 通过axios-cookiejar-support提供的方法创建带自定义配置的httpsAgent this.http.defaults.httpsAgent = new (axiosCookieJarSupport.getHttpsAgent(this.http))({ rejectUnauthorized: false })
说明
- 先创建基础axios实例,不设置
httpsAgent - 调用
wrapper启用CookieJar支持后,再用axios-cookiejar-support.getHttpsAgent()创建符合要求的Agent,传入你的自定义配置(如rejectUnauthorized: false) - 这种方式既保留了Cookie管理功能,又满足了自定义Agent的需求,无需使用axios其他特殊构造方法
内容的提问来源于stack exchange,提问作者Marius Magaud
相关产品推荐
相关产品推荐

