diff --git a/README.md b/README.md index b95cf88a..89162c98 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,13 @@ declare module 'axios' { See also https://github.com/axios/axios#request-config . +## FAQ + +- Q. Why can't I assign the httpAgent / httpsAgent? + - A. axios-cookiejar-support uses httpAgent / httpsAgent to read and write cookies. If other Agents are assigned, cookies cannot be read/written. +- Q. I want to use it with another Agent (e.g., http-proxy-agent). + - A. Consider using http-cookie-agent. axios-cookiejar-support also uses http-cookie-agent. Read http-cookie-agent's README for more details. + ## Contributing PRs accepted. diff --git a/src/__tests__/basic.spec.ts b/src/__tests__/basic.spec.ts index d079b0fa..6a25bbf0 100644 --- a/src/__tests__/basic.spec.ts +++ b/src/__tests__/basic.spec.ts @@ -215,3 +215,20 @@ test.serial('should throw error when config.jar was assigned with boolean', asyn t.plan(1); server.close(); }); + +test.serial('should allow to reuse config', async (t) => { + const { port } = await createTestServer([ + (_req, res) => { + res.end('Hello World!'); + }, + (_req, res) => { + res.end('Hello World!'); + }, + ]); + + const jar = new CookieJar(); + + const { config } = await axios.get(`http://localhost:${port}`, { jar, responseType: 'text' }); + await axios.get(`http://localhost:${port}`, config); + t.pass(); +}); diff --git a/src/index.ts b/src/index.ts index d6e5373c..4b897a24 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,8 @@ import type { AxiosInstance, AxiosRequestConfig, AxiosStatic } from 'axios'; import { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/http'; import type { CookieJar } from 'tough-cookie'; +const AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT = Symbol('AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT'); + declare module 'axios' { interface AxiosRequestConfig { jar?: CookieJar; @@ -18,12 +20,28 @@ function requestInterceptor(config: AxiosRequestConfig): AxiosRequestConfig { throw new Error('config.jar does not accept boolean since axios-cookiejar-support@2.0.0.'); } - if (config.httpAgent || config.httpsAgent) { + if ( + (config.httpAgent != null && config.httpAgent[AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT] !== true) || + (config.httpsAgent != null && config.httpsAgent[AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT] !== true) + ) { throw new Error('axios-cookiejar-support does not support for use with other http(s).Agent.'); } config.httpAgent = new HttpCookieAgent({ cookies: { jar: config.jar } }); + Object.defineProperty(config.httpAgent, AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT, { + configurable: false, + enumerable: false, + value: true, + writable: false, + }); + config.httpsAgent = new HttpsCookieAgent({ cookies: { jar: config.jar } }); + Object.defineProperty(config.httpsAgent, AGENT_CREATED_BY_AXIOS_COOKIEJAR_SUPPORT, { + configurable: false, + enumerable: false, + value: true, + writable: false, + }); return config; }