I am trying to access free API data using AXIOS module in NodeJS. Below is the code sample of the same and it is giving HTTP 401 status code - unauthorized
error.
Code Sample :
const axios = require('axios');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios);
const URL = `https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY`;
const getData = async (url) => {
console.log(`Get Data : `);
try {
const response = await axios.get(url, {withCredentials: true});
console.log(response);
} catch (error) {
console.error(error);
}
}
getData(URL);
I did try to use tough-cookie
npm module but ending up with same error everytime.
const axios = require('axios');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios);
const tough = require('tough-cookie');
const cookieJar = new tough.CookieJar();
const URL = `https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY`;
const getData = async (url) => {
console.log(`Get Data : `);
try {
const response = await axios.get(url, {withCredentials: true});
console.log(response);
} catch (error) {
console.error(error);
}
}
getData(URL);
const fetchData = async (url) => {
const response = await axios.get(url, {
headers: {
'accept': '*/*',
'User-Agent': 'Mozilla/5.0'
},
jar: cookieJar,
withCredentials: true // If true, send cookie stored in jar
});
console.log(response);
}
fetchData(URL);
Any help would be much appreciated, thanks in advance.
Building on Mohammad Yaser Ahmadi's answer:
The API is cookie-protected. The cookie is made available to you only if you visit the actual website. With that information in mind, we can automate this process by first making an axios call to the homepage so we can retrieve and store the cookie and then we can make subsequent requests to the API.
Axios example:
Axios example using
axios-cookiejar-support
andtough-cookie
: