Skip to content

Instantly share code, notes, and snippets.

@santosh-rumsan
Created November 19, 2019 04:48
Show Gist options
  • Save santosh-rumsan/979eb863af95f3b7202d200a33b6b9a2 to your computer and use it in GitHub Desktop.
Save santosh-rumsan/979eb863af95f3b7202d200a33b6b9a2 to your computer and use it in GitHub Desktop.
Using Axios to programmatically login to a website and requesting a secure page using cookies
const axios = require("axios").default;
const axiosCookieJarSupport = require("axios-cookiejar-support").default;
const tough = require("tough-cookie");
const qs = require("qs");
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
let loginAndGetContent = async () => {
try {
let login = await axios.post(
"https://mywebsite.com/login",
qs.stringify({
username: "{username}",
password: "{password}"
}),
{
jar: cookieJar,
withCredentials: true
},
{
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
}
);
await axios.get(
`http://mywebsite.com/securepage`,
{
jar: cookieJar,
withCredentials: true
}
);
} catch (e) {
console.log(e);
}
};
//run using node ./loginAndGetContent.js
loginAndGetContent()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment