Access NSE option chain API from Firebase Functions using axios

Viewed 29

I am trying to get NSE Option Chain json data from firebase functions using axios but request hangs on call.

NSE API is working fine on firebase-functions local development server,postman,chrome, but fails after deployment, not event giving error msg. Logs showing request timeout.

const functions = require("firebase-functions");
const admin = require('firebase-admin')
const axios = require('axios').default
admin.initializeApp(functions.config().firebase);

exports.getData = functions.region('asia-south1').https.onRequest(async (req, res) => {
    try {
        var resp = await axios({
            url: "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY",
            headers: {
                'Accept': '*/*',
                'Access-Control-Allow-Origin': '*',
            }
        })
        console.log(resp.data)
        res.json(resp.data)
    } catch (e) {
        console.log(e)
    }
    finally {
        return
    }
})

Google Cloud Functions Log

After suggestion I tried to get error msg like this...

try {
        var resp = await axios({
            url: process.env.URL,
            headers: {
                'Accept': '*/*',
                'Access-Control-Allow-Origin': '*',
            }
        })
        console.log(resp.data)
        res.json(resp.data)
    } catch (e) {
        functions.logger.error('error block')
        res.json({ e })
    }

getting response "Error: could not handle the request" in chrome

gcp logs screenshot

GCP logs not showing "error block", so its just timeout msg in chrome. Seems NSE API is rejecting request from gcp functions only for some reason.

replaced NSE API with another api https://jsonplaceholder.typicode.com/todos/1 and function works.

Seems the NSE API needs something specific in header which it gets from chrome and postman but not axios when deployed on google cloud functions.

1 Answers

The API must be returning an error but you are not terminating the function by returning a response. Try refactoring the code as:

exports.getData = functions.region('asia-south1').https.onRequest(async (req, res) => {
  try {
    var resp = await axios({
      ...
    })
    console.log(resp.data)
    res.json(resp.data)
  } catch (e) {
    console.log(e)
    // Return error only for testing
    res.json({
      e
    })
  }
})

This way the function will terminate even if an error is thrown and you should be able to check it.

Related