GithubHelp home page GithubHelp logo

3846masa / axios-cookiejar-support Goto Github PK

View Code? Open in Web Editor NEW
304.0 3.0 55.0 2.57 MB

Add tough-cookie support to axios.

License: MIT License

JavaScript 8.41% TypeScript 87.53% Shell 4.06%
axios tough-cookie cookiejar axios-ecosystem

axios-cookiejar-support's People

Contributors

3846masa avatar renovate[bot] avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

axios-cookiejar-support's Issues

Bug (Maybe) cookies are duplicated on subsequent redirects

I am not sure if this is a bug yet, trying to reproduce and write some tests, but cannot due to #227

But figured I'll open an issue, just in case, maybe you can spot the error, if there is one.

Here is a sanitized request flow:

GET /url1 HTTP/1.1
Cookie: cookiename=111111;
Host: example.com


HTTP/1.1 302 Found
Location: https://example.com/url2


GET /url2 HTTP/1.1
Cookie: cookiename=111111; cookiename=111111;
Host: example.com


HTTP/1.1 302 Found
Location: /url3
Set-Cookie: cookiename=222222; Domain=example.com; Expires=Thu, 10-Nov-2039 23:46:26 GMT; Path=/


GET /url3 HTTP/1.1
Cookie: cookiename=111111; cookiename=111111; cookiename=222222;
Host: example.com

Notice that with each request the cookies get appended and they have duplicate names.

Cookie not in this host's domain

I'm trying to store instagram cookies

const axios = require('axios').default
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const tough = require('tough-cookie')

axiosCookieJarSupport(axios)
const cookieJar = new tough.CookieJar()
axios.defaults.jar = cookieJar
axios.defaults.withCredentials = true

exports.getProfilePic = async (req, res, next) => {
  const baseUrl = 'https://www.instagram.com/'
  const response = await axios.get(baseUrl)
  console.log(response.config.jar.toJSON())
  res.json(cookieJar)
}

I get this error

Error: Cookie not in this host's domain. Cookie:i.instagram.com Request:www.instagram.com

The base URL is https://www.instagram.com/ and I get some cookies fromi.instagram.com

Is it possible to store subdomains cookies?.

Semver error in peer dependecies

When installing axios-cookiejar-support as a dependency, if you have an axios version higher than 0.20.0 you will get this error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: @millenniumearl/[email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/axios
npm ERR!   axios@"^0.21.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer axios@"^0.20.0" from [email protected]
npm ERR! node_modules/axios-cookiejar-support
npm ERR!   axios-cookiejar-support@"^2.0.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

The problem (if not intentional) could come from the fact that in the peer dependencies the required version of axios is ^0.20.0. As the module has not yet reached version 1.0.0, this problem may occur.

Cannot enable destructuring assignment to axios methods when apply this library

Hi,

I cannot use tough cookie jar support v 0.5.0 with axios 0.19.0. on Noe.js v10.13.0

I have tried the example you have in the README.md but it is not working for me:

const axios = require('axios').default;

const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const tough = require('tough-cookie');

const instance = axios.create({
  // WARNING: This value will be ignored.
  jar: new tough.CookieJar(),
});

// Set directly after wrapping instance.
axiosCookieJarSupport(instance);
instance.defaults.jar = new tough.CookieJar();


const { get, post } = instance;

The code fails here:

https://github.com/3846masa/axios-cookiejar-support/blob/master/workspaces/axios-cookiejar-support/lib/index.mjs#L59

In the packaged lib its L73 in /lib/index.js:

Screen Shot 2019-07-01 at 11 28 48

EDIT:

fixed it by using instance instead of this in the anonymous function:

PR: #190

Rewrite with async/await

For readability, rewrite with async/await.


  • Rewrite with async/await
  • Setup transpiler
    • TypeScript or Babel?
      • babel v7 + babel-env + fast-async
      • TypeScript

@types/tough-cookie ^2.3.3 to ^4.0.0 release

be87d1e updates @types/tough-cookie from ^2.3.3 to ^4.0.0. This change isn't in the latest npm release of this package yet.
Consuming the package with the stale dependency can result in the following TypeScript error:

error TS2322: Type 'CookieJar' is not assignable to type 'boolean | CookieJar'.
  Type 'import("node_modules/@types/tough-cookie/index").CookieJar' is not assignable to type 'import("node_modules/axios-cookiejar-support/node_modules/@types/tough-cookie/index").CookieJar'.

The fix in the mean time is to downgrade @types/tough-cookie to ^2.3.3 in the project consuming axios-cookiejar-support or manually updating the npm shrinkwrap for the package.

Releasing a new version based on the current master branch should resolve the issue.

Thanks for writing this package. πŸŽ‰

maxRedirects set to 0 and 3xx throw errors

Hello,

I'm just following up on #161.

As said in the last comment, validateStatus is removed and never restored.
Also, maxRedirects is set to 0.

When i use the axios-retry plugin, 3xx statuses throw an error.
This happens because axios-cookiejar-support mutates the request config (sets maxRedirects to 0). This config is passed to the retried request which throws an error if the response status is 3xx.

Whats the reason behind :

Object.assign(config, {
    maxRedirects: 0,
});
delete config.validateStatus;

Thanks in advance.

error TS2339: Property 'jar' does not exist on type 'AxiosRequestConfig'.

I am using axios with TypeScript (because it has typings) and now I want to apply "axios-cookiejar-support".

Unfortunately, there are no type definitions for "axios-cookiejar-support", so TypeScript complains because "axios-cookiejar-support" wants to add a property ("jar") to the axios config which is not defined in axio's typings:

error TS2339: Property 'jar' does not exist on type 'AxiosRequestConfig'.

Source code for axio's typings is:

Broken code:

public sendRequest(config: AxiosRequestConfig): AxiosPromise {
  config.baseURL = this.baseURL;
  config.jar = this.cookieJar;
  return axios.request(config);
}

I can only fix it with any which will remove the benefits of having types:

public sendRequest(config: any): AxiosPromise {
  config.baseURL = this.baseURL;
  config.jar = this.cookieJar;
  return axios.request(config);
}

jar not fully working

This jar support for axios is not working with shopping carts that relies on cookies. I switched to 'request' package to proceed with my project.

Redirections are followed on non-redirect status codes

if (local.redirectCount >= 0 && !!headers['location']) {

This code here seems to ignore the statuscode returned, and will follow a redirect.
This becomes an issue when a Location header is set on a 201 Created response and the user may not want to follow that redirect.

For now I think I can work around this by setting {maxRedirects : 0} in the config per request, but its not a very nice solution.

Broken in typescript & node: `TypeError: axios_cookiejar_support_1.default is not a function`

typescript 2.6.2, axios-cookiejar-support v0.2.1, node lts/boron and node lts/carbon.
this ts code:

import axiosCookieJarSupport from "axios-cookiejar-support";
axiosCookieJarSupport(Axios);

Is transpiled to

const axios_cookiejar_support_1 = require("axios-cookiejar-support");
axios_cookiejar_support_1.default(axios_1.default);

which throws

axiosCookieJarSupport(Axios);
                     ^
TypeError: axios_cookiejar_support_1.default is not a function

See microsoft/TypeScript#5565

The solution would be to change the d.ts file and remove the default export.

Error: axios-cookiejar-support does not support for use with other http(s).Agent.

How can I use both cookies and HTTPS Agent configuration?

I use Axios like this and I need to disable CA checks:

const
    axios = require('axios').default,
    { wrapper } = require('axios-cookiejar-support'),
    { CookieJar } = require('tough-cookie');

wrapper(axios);
axios.defaults.jar = new CookieJar();
axios.defaults.withCredentials = true;
axios.defaults.httpsAgent = new https.Agent({
    keepAlive: true,
    rejectUnauthorized: false, // disable CA checks
});
axios.defaults.headers.common = {
    "User-Agent": "HTTPie/2.3.0",
    "Accept": "*/*"
};

I get the not supported error. Can you please suggest how to use axios-cookiejar-support in this scenario?

Context: https://github.com/schlomo/chromebooks-in-deutschland/blob/master/functions/backend.js#L16 and I am trying to upgrade my dependencies

Environments

  • OS: macOS
  • Node.js version: 16.10.0
  • axios version: 2.0.3
  • tough-cookie version: 4.0.0

Thanks a lot!

Error: Cannot find module 'axios-cookiejar-support'

When I use npm i axios axios-cookiejar-support to install and use this package, it throws axios-cookiejar-support when I trying to require('axios-cookiejar-support'); under node v8.1.2.

I looked into the node_modules/axios-cookiejar-support and find that none of your files has been compiled and they leaved as .mjs files. Meanwhile, package.json says that the main file of this module is ./lib/index.

When we require modules using require funtions, it can not require esm modules even in the latest nodejs. I can only use import synatx and with the very new nodejs if I want to use your package but this never mentioned in anywhere of your docs.

I found that you have babel and build scripts in your repo. So here is the question: why you keep compiled .js files out of the npm publish? (They are ignored by .gitignore, which will be used as .npmignore if there is not one.)

Unable to save cookies when using axios.create()

When using axios.create to set up a client, none of the cookies get saved for me due to the following error:

(node:1484) UnhandledPromiseRejectionWarning: Error: Cookie not in this host's domain. Cookie:domain.example Request:null

This appears to be because on the following lines, it appears to be only passing in the path of the URL and not including the baseURL:

setCookiePromiseList.push(setCookie(cookie, config.url));

setCookiePromiseList.push(setCookie(cookie, config.url));

Changing the lines to the following (as a hotfix) seems to have solved my problem:

setCookiePromiseList.push(setCookie(cookie, config.baseURL + config.url));

any way to use it on the react native

I am trying to use this library on react native. But the library is using this function
function noopEnableCookieJarSupport (instance) {
return instance;
}.
So, is there anyway to use it on react-native ?

Error: Cannot read property 'set-cookie' of undefined

If axios-cookiejar-support is used and the API service is down, an error occurs during the interceptor from this library, masking the real error.

For example, the response contains the following message:'connect ECONNREFUSED XXXXX'

The response interceptor will try to access response.headers['set-cookie'] but headers is undefined since it failed to connect. We need an additional check to ensure the headers is valid before trying to access 'set-cookie'.

image

cookies not showing in browser

I followed the examples provided in the git repo, and it works fine in nodejs. When I print out the cookies using console.log(cookieJar.toJSON()) in nodejs it shows the cookies

But when I run this in the browser using reactjs/nextjs, after the api call, printing output using console.log(cookieJar.toJSON()) does not show any cookies. Also in the browser when I print using console.log(axiosCookieJarSupport), I see:

function noopEnableCookieJarSupport (instance) {
return instance;
}

Is there a reason this does not work in the browser? Is there a way to make this work in the brrowser?

Secured cookie not sent

Hello, i use version 0.5.1of axios-cookiejar-support. I connect on page A. It answers cookie like this :

sessionId=xxxx; Path=/; Secure

Then, i need this sessionId allowing me to connect another page B but it is never sent. After checking my raw request headers, Cookie is absent. By default, tough-cookie does not provide secured cookie.

const tough = require('tough-cookie');
const Cookie = tough.Cookie;

const securedCookie = Cookie.parse('sessionId=xxxx; Path=/; Secure');
const simpleCookie = Cookie.parse('key=value; Path=/');

const url = 'http://www.example.com/';
const cookieJar = new tough.CookieJar();

cookieJar.setCookie(securedCookie, url, () => { });
cookieJar.setCookie(simpleCookie, url, () => { });

cookieJar.getCookies(url, (err, cookies) => {
    //Output : key=value
    console.log(cookies.map(cookie => cookie.cookieString()).join('; '));
});

cookieJar.getCookies(url, { secure: true }, (err, cookies) => {
    //Output : sessionId=xxxx; key=value
    console.log(cookies.map(cookie => cookie.cookieString()).join('; '));
});

So, i think an option which authorizes secured cookie is to add. Thanks in advance :)

validateStatus doesn't work

Hello,
with this plugin, validateStatus parameter is ignored.
For example (the url called necessarily returns an error 500)

try {
	axios.defaults.validateStatus = () => true;
	const result = await axios.get(`/ws/lieux-vente/RUN/stocks/14`);
	console.log(result); // NOT DISPLAYED WITH THIS PLUGIN
catch (err){
	console.error(error); // DISPLAYED WITH THIS PLUGIN, THIS SHOULD NOT BE THE CASE
}

After moving to latest release, I am getting an error: The "url" argument must be of type string

code:'ERR_INVALID_ARG_TYPE'
message:'The "url" argument must be of type string. Received undefined'
stack:'TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received undefined

I went from v1.01 to latest 2.0.1 version and did all the work outlined in the migration doc.

import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';

const request = axios.create({
  jar: new CookieJar()
  }):
  wrapper(request);

const url = 'https://actualUrl';
request.post(url, {data: abc});

If I move back to v1.0.1 and change the import back, it works fine. The rest of the code is the same.

POST with Body Not Passing Cookies

I have a POST that contains a body, and for some reason, the Cookies aren't getting injected into the request. What did I do wrong here:

return axios
    .post(
        urlJoin(
            config.portal.url,
            'Account/Register'),
        {
            UserName: "[email protected]",
            UserFirstName: "First Name",
            UserLastName: "Last Name",
            Email: "[email protected]",
            Password: "...",
            ConfirmPassword: "..."
        },
        {
            jar: cookieJar,
            withCredentials: true
        })
    .then(res => callback())
    .catch(err => callback(err))

The weird part is, if I perform a GET against the same endpoint the Cookies get passed:

return axios
    .get(
        urlJoin(
            config.portal.url,
            'Account/Register'),
        {
            jar: cookieJar,
            withCredentials: true
        })
    .then(res => callback())
    .catch(err => callback(err));

Also, if I perform a POST without a body, they get passed:

.post(
    urlJoin(
        config.portal.url,
        `Account/LoginApi?UserName=${config.portal.userName}&Password=${config.portal.password}`),
    null,
    {
        jar: cookieJar,
        withCredentials: true
    })
.then(res => callback())
.catch(err => callback(err))

Axios config.baseURL is lost in redirect

If I have an Axios instance that has a baseURL, it is lost with axios-cookiejar-support and thus stops working. Imagine the following pseudo code

const http = require('http')
const express = require('express')
const axios = require('axios')
const tough = require('tough-cookie')

require('@3846masa/axios-cookiejar-support')(axios)

const app = express()

app.get('/foo', (req, res) => res.redirect('/bar'))
app.get('/bar', (req, res) => res.send('bar'))

describe('/foo', () => {
  let server
  let request

  beforeEach((done) => {
    let s = http.createServer(app)
    server = s.listen(0, () => { // random port
      let port     = s.address().port
      let baseURL  = `http://127.0.0.1:${port}`
      let jar      = new tough.CookieJar()
      let config   = {
        baseURL,
        jar,
        withCredentials: true,
        validateStatus(status) {
          return true
        }
      }

      request = axios.create(config)
      done()
    })
  })

  afterEach(() => server.close())

  it('redirect', async () => {
    let res = await request.get('/foo')

    assert(res.data === 'bar')
  })
})

The test will fail with the following output

    0 passing (53ms)
    1 failing

    1) foo redirect:
       Error: connect ECONNREFUSED 127.0.0.1:80
        at Object.exports._errnoException (util.js:1016:11)
        at exports._exceptionWithHostPort (util.js:1039:20)
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1138:14)

Debug through can find that there were two request going out

// origin request
http://127.0.0.1:52815/foo

// redirect request
http://127.0.0.1/bar

Trace the code and found that we are explicitly setting config.baseURL = undefined here: https://github.com/3846masa/axios-cookiejar-support/blob/master/lib/response-interceptor-wrapper.js#L37

What are the reasoning behind this resetting of config.baseURL? Can we remove that line?

Request failed with status code 301

Adding axiosCookieJarSupport leads to redirects fail (for example on https://google.com/).

With simple code:

const axios = require('axios');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const tough = require('tough-cookie');
const HttpsProxyAgent = require('https-proxy-agent');
const HttpProxyAgent = require('http-proxy-agent');

axiosCookieJarSupport(axios);

async function(page, proxy) {
    const cookieJar = new tough.CookieJar();

    const httpsAgent = new HttpsProxyAgent(httpsAgentConfig);
    const httpAgent = new HttpProxyAgent(httpAgentConfig);

    page.on("request", async (req) => {
    const resp = await axios({
          url: req.url(),
          method: req.method(),
          headers,
          data: req.postData(),
          timeout: 30000,
          responseType: 'stream',
          proxy: false,
          httpsAgent,
          httpAgent,
          jar: cookieJar,
          withCredentials: true,
        });
    //...
    }
}

REQUEST ERROR https://google.com/ Request failed with status code 301

adding/removing httpAgent and httpsAgent doesn't change anything. without axiosCookieJarSupport everything works fine

Issue with hanging request

Hi thanks for creating this library it's just what i'm looking for!

I'm attempting to use this solution on an API which returns a 302 initially with a set-cookie JSESSIONID which is then needed on subsequent requests.

My issue is that i'm unfortunately getting timed out on my requests after I add the code

import axios from 'axios';
import axiosCookieJarSupport from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';

const cookieJar = new CookieJar()

axiosCookieJarSupport(axios)
const result = await axios.post(`${baseUrl}${endpoints.insertOrder}`, form, {
	headers: {
		'content-type': `multipart/form-data; boundary=${form.getBoundary()}`,
	},
	jar: cookieJar,
	withCredentials: true
});

I've tried the following with the request library and it works fine - am I missing something?

const res = await requestPromise({
	method: 'POST',
	followAllRedirects: true,
	uri: `${baseUrl}${endpoints.insertOrder}`,
	form: {
		...order,
		products: JSON.stringify(order.products),
	},
	headers: {
		'Content-Type': 'multipart/form-data',
	},
	jar: true,
	withCredentials: true,
	resolveWithFullResponse: true,
});

axios-cookiejar-support redirect method not consistent with axios redirect method

When submitting request via axios to a url that returns redirect status codes 301, 302, 303, 307 or 308, axios will call the redirected location using the original method eg. HEAD, GET, POST, etc. When submitting request using axios with axios-cookiejar-support, the method to the redirected location is set to GET except for 307 status. This is partially consistent with browser behavior explained below except 308 status should also retain original method on redirect:

https://stackoverflow.com/questions/2068418/whats-the-difference-between-a-302-and-a-307-redirect#:~:text=302%20is%20temporary%20redirect%2C%20which,response%20generated%20by%20the%20browser.

I think the code handling this is in node_modules\axios-cookiejar-support\lib\interceptors\response.js on line 59:

if (local.redirectCount >= 0 && (0, _isRedirect.default)(statusCode) && !!headers['location']) {
if (response.status !== 307) {
config.method = 'get';
}

Question: Should axios-cookiejar-support handle redirect responses the same way that axios handles redirect responses?

Here is code based on axios unit test (https://github.com/axios/axios/pull/1758/commits) I used to test with and without coookie jar support for different redirect codes:

const axios = require('axios').default;

const useCookieJar = true;
const redirectStatus = 308;

if (useCookieJar) {
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios);
}

//testing axios redirect
const http = require('http');
const urllib = require('url');
let server = http.createServer(function (req, res) {
if (req.method.toLowerCase() !== "head") {
res.statusCode = 400;
res.end();
return;
}

let parsed = urllib.parse(req.url);
if (parsed.pathname === '/one') {
	res.setHeader('Location', '/two');
	res.statusCode = redirectStatus;
	res.end();
} else {
	res.end();
}

}).listen(4444, function () {
axios('http://localhost:4444/one',{method:'head'})
.then(function (res) {
console.log(res.status);
}).catch(function (err) {
console.error(err);
console.error('redirected request does not maintain original method');
});
});

console.log(response);

Extremely Minor Request: "Normal" NPM Package

Fist off thanks so much for adding cookie support to Axios. However, I have one very minor request: a "normal" package name.

I know that:

"@3846masa/axios-cookiejar-support": "^0.1.1",

is a perfectly legit NPM package ... but when you see it in a long list of package names that have neither "@" nor "/" it look like you're using some strange amateur-written code in the middle of your otherwise professional dependency list.

Any chance you could "normalize" axios cookie jar support's NPM package name? If not it's (obviously) not important, but I figured it couldn't hurt to ask.

Unknown Plugin: "module:@babel/plugin-transform-modules-commonjs"

looking at the .babel.rc file in axios-cookie-jar-support directory, plugins is defined as:
{ "plugins": [ "module:@babel/plugin-transform-modules-commonjs", [ ..... }

Looking at the babel/plugin-transform-modules-commonjs documentation page,(https://babeljs.io/docs/en/next/babel-plugin-transform-modules-commonjs)

It states that plugin-transform-modules-commonjs (without options) should be loaded as
"plugins": ["@babel/plugin-transform-modules-commonjs"] }

Upon removing the "module: "portion in the .babel.rc file found in axios-cookiejar-support, the code compiles again. Is this a possible error or am I not declaring something on my machine that will also note plugin-transform-modules-commonjs as a module?

Does not play well with kuitos/axios-extensions

I'm creating issues on both this repo and kuitos/axios-extensions hoping that someone either here or there will have some ideas.

Basically I have this:

const axios = require('axios')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const axiosExtensions = require('axios-extensions')
const LRUCache = require('lru-cache')

// Even tried specifying my own cookie jar
// const tough = require('tough-cookie')
// let cookiejar = new tough.CookieJar()

axiosCookieJarSupport(axios)

let cache = new LRUCache({ maxAge: 300000 })

let cacheAdapter = axiosExtensions.cacheAdapterEnhancer(axios.defaults.adapter, {
  defaultCache: cache,
  enabledByDefault: true
})

let instance = axios.create({
  adapter: cacheAdapter,
  baseURL: 'http://example.com',
  headers: {
    'Cache-Control': 'no-cache'
  },
  jar: true, // cookiejar,
  withCredentials: true
})

// Results in error
instance.get('/')
  .then(r => instance.get('/'))
  .then(r => console.log(r))
  .catch(e => console.error(e))

// This results in an error as well
// async function test() {
//   try {
//     var r1 = await instance.get('/')
//     console.log(r1)
//     var r2 = await instance.get('/')
//     console.log(r2)
//   } catch (e) {
//     console.error(e)
//   }
// }
// test()

The first request works fine (because there's not a cached version of the request) but then the second one (cached) results in the following error:

TypeError: Cannot read property 'jar' of undefined
    at /my-project/node_modules/axios-cookiejar-support/lib/interceptors/response.js:28:15
    at new Promise (<anonymous>)
    at responseInterceptor (/my-project/node_modules/axios-cookiejar-support/lib/interceptors/response.js:21:10)
    at instance.interceptors.response.use.res (/my-project/node_modules/axios-cookiejar-support/lib/index.js:47:67)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

As soon as I remove either config.adapter or config.jar, everything works fine.

I'm having a hard time thinking of how this should even function. I guess that after the requests are cached then cookies are no longer required and should be ignored. Or maybe cached as well?

I'm going to keep playing with both packages and try to figure something out but if anyone has any ideas I'd greatly appreciate it. 😁

Issue on the other repo: kuitos/axios-extensions#33

Redirects not followed and 3xx responses are thrown as errors

Hey Masahiro,

It seems that all redirects are returned as errors. This is not the default behavior for axios.
It is, however, possible to bypass this by adding the following after calling axiosCookieJarSupport(axios):

axios.defaults.validateStatus = function(status) {
	return status >= 200 && status < 400
}

However, no matter how I tried editing the maxRedirects option (global config/individual request settings) it never seems to follow redirects thus leaving me stuck with 301 response data :<>

Just a heads up to you. I'll try to have a PR with a solution in the next few days.

URL not filled on cookie jar store after updating to version 2.0.2

After I updated to version 2.0.2 the urls inside the memorystorage of tough-cookie are all null.

Before update (1.0.1):

const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const { CookieJar } = require('tough-cookie');
....
const cookieJar = new CookieJar();
axios.defaults.jar = cookieJar;
axios.defaults.withCredentials = true;

await axios.get(xxxxx);

Inside the CookieJar:
image

After Update:

const { wrapper } = require('axios-cookiejar-support');
const { CookieJar } = require('tough-cookie');
...
wrapper(axios);
const cookieJar = new CookieJar();
axios.defaults.withCredentials = true;


await axios.get(xxxxx, { jar: cookieJar });

Inside CookieJar:
image

It seems like it is saving the cookie under url "null", so there must be something wrong with accessing the url from axios.

More info:
Nodejs : 12.13.1
Axios: 0.21.4

Can't use with react-native?

I'm trying to add cookiejar support to axios in react-native. After installing with
npm install --save axios-cookiejar-support the react-native bundler breaks with the following error:

error: bundling failed: ReferenceError: Unknown plugin "module:@babel/plugin-transform-modules-commonjs" specified in "/Users/.../[project]/node_modules/axios-cookiejar-support/.babelrc" at 0, attempted to resolve relative to "/Users/.../[project]/node_modules/axios-cookiejar-support"

I can see that the axios-cookiejar-support .bablerc file does contain that plugin, and its listed under devDependencies in the package.json. Running npm install --save @babel/plugin-transform-modules-commonjs in the [project]/node_modules/axios-cookiejar-support directory has to effect. Any idea how to resolve this?

Break app when not importing Axios defaults

Apparently, if Axios is used like this when axios-cookiejar-support is part of an app, then it breaks:

import { request } from "axios";
request({
  url: "https://www.google.be",
}).then(r => console.log(r));

Here's the error that I get:

/home/sebastien/wks/didowi/node_modules/axios-cookiejar-support/lib/index.js:58
    const mergedConfig = mergeConfig(_defaults.default, mergeConfig(this.defaults, config));
                                                                         ^
TypeError: Cannot read property 'defaults' of undefined
    at request (/home/sebastien/wks/didowi/node_modules/axios-cookiejar-support/lib/index.js:58:74)
    at Module../apps/gate/src/main.ts (/home/sebastien/wks/didowi/dist/apps/gate/webpack:/apps/gate/src/main.ts:50:8)
    at __webpack_require__ (/home/sebastien/wks/didowi/dist/apps/gate/webpack:/webpack/bootstrap:19:1)
    at Object.0 (/home/sebastien/wks/didowi/dist/apps/gate/main.js:29245:18)
    at __webpack_require__ (/home/sebastien/wks/didowi/dist/apps/gate/webpack:/webpack/bootstrap:19:1)
    at /home/sebastien/wks/didowi/dist/apps/gate/webpack:/webpack/bootstrap:83:1
    at Object.<anonymous> (/home/sebastien/wks/didowi/dist/apps/gate/main.js:87:10)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)

I think that this package is added to my application through nano, the client library for CouchDB: https://github.com/apache/couchdb-nano.

Here's what they're doing with it: https://github.com/apache/couchdb-nano/pull/245/files

I'm facing this issue while working on something completely different by the way: auth0/node-jwks-rsa#215

Any idea how to fix this? Should the node-jwks-rsa library use import Axios like this? const axios = require('axios').default; or is it supposed to work if they do import { get } from "axios"; ?

How to run tests?

git clone ...
npm i
npm t
❯ npm t

> [email protected] test .../axios-cookiejar-support
> mocha test.spec.js --require intelli-espower-loader

Error: Cannot find module './'
  at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
  at Function.Module._load (internal/modules/cjs/loader.js:508:25)
  at Module.require (internal/modules/cjs/loader.js:637:17)
  at require (internal/modules/cjs/helpers.js:22:18)
  at Object.<anonymous> (.../axios-cookiejar-support/test.spec.js:9:31)
  at Module._compile (internal/modules/cjs/loader.js:701:30)
  at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
  at Object.extensions..js (.../axios-cookiejar-support/node_modules/espower-loader/index.js:47:13)
  at Module.load (internal/modules/cjs/loader.js:600:32)
  at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
  at Function.Module._load (internal/modules/cjs/loader.js:531:3)
  at Module.require (internal/modules/cjs/loader.js:637:17)
  at require (internal/modules/cjs/helpers.js:22:18)
  at .../axios-cookiejar-support/node_modules/mocha/lib/mocha.js:334:36
  at Array.forEach (<anonymous>)
  at Mocha.loadFiles (.../axios-cookiejar-support/node_modules/mocha/lib/mocha.js:331:14)
  at Mocha.run (.../axios-cookiejar-support/node_modules/mocha/lib/mocha.js:809:10)
  at Object.exports.singleRun (.../axios-cookiejar-support/node_modules/mocha/lib/cli/run-helpers.js:108:16)
  at exports.runMocha (.../axios-cookiejar-support/node_modules/mocha/lib/cli/run-helpers.js:142:13)
  at Object.exports.handler.argv [as handler] (.../axios-cookiejar-support/node_modules/mocha/lib/cli/run.js:292:3)
  at Object.runCommand (.../axios-cookiejar-support/node_modules/yargs/lib/command.js:242:26)
  at Object.parseArgs [as _parseArgs] (.../axios-cookiejar-support/node_modules/yargs/yargs.js:1087:28)
  at Object.parse (.../axios-cookiejar-support/node_modules/yargs/yargs.js:566:25)
  at Object.exports.main (.../axios-cookiejar-support/node_modules/mocha/lib/cli/cli.js:68:6)
  at Object.<anonymous> (.../axios-cookiejar-support/node_modules/mocha/bin/mocha:164:29)
  at Module._compile (internal/modules/cjs/loader.js:701:30)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
  at Module.load (internal/modules/cjs/loader.js:600:32)
  at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
  at Function.Module._load (internal/modules/cjs/loader.js:531:3)
  at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
  at startup (internal/bootstrap/node.js:283:19)
  at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! Test failed.  See above for more details.

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Unfortunately this error doesn't have any additional information. Feel free to kindly ask the author of the @semantic-release/exec plugin to add more helpful information.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Unhelpful Message on TypeError: Cannot read property 'backupOptions' of undefined

When you get a TypeError: Cannot read property 'backupOptions' of undefined it's because of this code:

const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.backupOptions = local.backupOptions || {};

If config._COOKIEJAR_SUPPORT_LOCAL is missing then (unsurprisingly) undefined.backupOptions will result in an error.

However, when this happens it's obvious that the plug-in isn't being applied, because otherwise config._COOKIEJAR_SUPPORT_LOCAL would be present. However, that fact is not obvious to a new user (I only figured it out by reading the code).

Therefore a more helpful error message would tell the user what they did wrong, or at least give them a general idea. Something to the effect of "Hey dummy you forgot to include jar: cookieJar in your axios config or you forgot to wrap your axios instance with axiosCookieJarSupport" would make this error much less painful to someone trying to use the plugin for the first time.

TypeError: Cannot read property 'backupOptions' of undefined

TypeError: Cannot read property 'backupOptions' of undefined
    at backupOriginalConfigs (/home/landan/www/adonuxt-rp/node_modules/@3846masa/axios-cookiejar-support/lib/request-interceptor-wrapper.js:7:32)
    at process._tickCallback (internal/process/next_tick.js:109:7)
    at Module.runMain (module.js:607:11)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
const axios = require('axios')
const axiosCookieJarSupport = require('@3846masa/axios-cookiejar-support')
const tough = require('tough-cookie')
axiosCookieJarSupport(axios)

const cookieJar = new tough.CookieJar()

//[...]
getInstanceGitInfo () {
    let options = {}
    options.headers = {}

    options.headers['Accept'] = 'application/json'
    options.headers['Content-Type'] = 'application/json'
    options.headers['X-Requested-With'] = 'XMLHttpRequest'

    let api = axios.create(options)

    // https://github.com/mzabriskie/axios#interceptors
    api.interceptors.response.use(function (response) {
      return response.data || response
    }, function (error) {
      return Promise.reject(error)
    })

    return api({
      method: 'post',
      url: 'http://www.example.com/login',
      jar: cookieJar,
      withCredentials: true,
      data: {
        username: 'user',
        password: 'xxxxxxx'
      }
    })
    .then(() => {
      return api.get('http://www.example.com/admin/system/info', { jar: cookieJar, withCredentials: true })
    })
    .catch(err => {
      console.log(err)
    })
  }

I'm unsure why I'm getting this error

Get / Set Store

Hi I was wondering if there is a way I could , use a store, save it in db and reuse it later?

Something like
First Request
axiosCookieSuport(axios);
const cookieJar = new tough.CookieJar();
let apiCookie = { withCredentials: true, jar: cookieJar };
saveToDb(apiCookie);
Second Request
let storedSession = myDb.getSession(); //This is apiCookie
apiCookie = storedSession.

I have the infrastructure for db etc. I just need to know how to set / get store from cookiejar.

calling `axiosCookieJarSupport(axios)` more than once seems to break axios

I built a small utility library that will authenticate to a service and return the cookie jar, for use in other requests.

In my apps which use this library, if I load axios and call axiosCookieJarSupport(axios);, all requests will fail with:

name=RangeError, message=Maximum call stack size exceeded, stack=RangeError: Maximum call stack size exceeded
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:247:15)
    at assignValue (C:\EDSS\node_modules\axios\lib\utils.js:251:21)
    at forEach (C:\EDSS\node_modules\axios\lib\utils.js:224:12)
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:258:5)
    at assignValue (C:\EDSS\node_modules\axios\lib\utils.js:251:21)
    at forEach (C:\EDSS\node_modules\axios\lib\utils.js:224:12)
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:258:5)
    at assignValue (C:\EDSS\node_modules\axios\lib\utils.js:251:21)
    at forEach (C:\EDSS\node_modules\axios\lib\utils.js:224:12)
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:258:5)
    at assignValue (C:\EDSS\node_modules\axios\lib\utils.js:251:21)
    at forEach (C:\EDSS\node_modules\axios\lib\utils.js:224:12)
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:258:5)
    at assignValue (C:\EDSS\node_modules\axios\lib\utils.js:251:21)
    at forEach (C:\EDSS\node_modules\axios\lib\utils.js:224:12)
    at merge (C:\EDSS\node_modules\axios\lib\utils.js:258:5)

The fix for this is to allow my library to call axiosCookieJarSupport(axios); and then ensure no downstream users ever call it again. This isn't a huge deal for me, but I think this library could handle this case.

Should calling axiosCookieJarSupport(axios); multiple times result in no operation performed, or maybe a warning log, or exception thrown?

baseURL causes cookie not in host's domain

The config.url passed to CookieJar does not include the baseURL and causes tough-cookie not knowing what the domain is and causing error. I would suggest combining the baseURL and the config.url or getting the url from somewhere else.

CookieJar cannot be passed at [email protected]

import _axios from 'axios';
import axiosCookieJarSupport from 'axios-cookiejar-support';
import { LazyCookieJar } from 'lazy-cookies';
import toughCookie from 'tough-cookie';

export const axios = axiosCookieJarSupport(_axios) as typeof _axios;

let a = axios.create({
	//jar: new LazyCookieJar(),
	jar: new toughCookie.CookieJar(),
});

console.dir(a.defaults.jar);
// => undefined

The plugin will cause a Maximum Call Stack Exceeded error when using an https.Agent

When adding an https.Agent to the config and then including this library, the process will hit the maximum allowed callstack of the nodejs process. This is because of the redirect behavior in the request interceptor.

The only way to get around this bug is to only include the https.Agent in the request level config and not the global or instance configs. This is super annoying if you want to provide your client as a library since your consumer would then need to add the https.Agent to each of their requests. Ugh.

Error: Cannot find module 'axios/lib/utils'

Hello!

I recently updated the module from 0.4.2 to 1.0.0 in my Electron app.
Now, this error is showed after I build and start the app :

A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module 'axios/lib/utils'

It is working when I'm in dev mode, the build is created, and it was also working before the update.
I think it's from the require('axios/lib/utils') in the code (?)

Any idea to help me ?
Thanks :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.