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

1.3k views Asked by At

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.

2

There are 2 answers

0
knicola On BEST ANSWER

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))
0
Mohammad Yaser Ahmadi On

you need to copy manually and paste cookie for request like the following photo in 6 step enter image description here

after that send your request like this:

var axios = require("axios");

async function request() {
  var config = {
    method: "get",
    url: "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY",
    headers: {
      Connection: "keep-alive",
      "Accept-Encoding": "gzip, deflate, br",
      cookie:'paste the cookie',
    },
  };
  try {
    const response = await axios(config);
    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

request();