Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

node.js - 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.

question from:https://stackoverflow.com/questions/66062257/unauthorized-error-when-trying-to-access-an-api-using-axios-in-nodejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...