Search code examples
node.jsecmascript-6axiosaxios-cookiejar-support

Unauthorized error when trying to access an API using AXIOS in NodeJS


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.


Solution

  • 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:

    const axios = require('axios').default;
    axios.get('https://www.nseindia.com/')
        .then(res => {
            return axios.get('https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY', {
                headers: {
                    cookie: res.headers['set-cookie'] // cookie is returned as a header
                }
            })
        })
        .then(res => console.log(res.data))
        .catch(res => console.error(res.response.data))
    

    Axios example using axios-cookiejar-support and tough-cookie:

    const axios = require('axios').default;
    const axiosCookieJarSupport = require('axios-cookiejar-support').default;
    const tough = require('tough-cookie');
    const instance = axios.create({ withCredentials: true });
    axiosCookieJarSupport(instance);
    instance.defaults.jar = new tough.CookieJar();
    
    instance.get('https://www.nseindia.com/')
        .then(res => instance.get('https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY'))
        .then(res => console.log(res.data))
        .catch(res => console.error(res.response.data))