Rizwan Malik
Rizwan Malik

Reputation: 21

Node.js changing type of variable from Object to Undefined

I am trying to make API call from Node.js Expressjs. API call is working fine however after parsing the response to JSON, when I try to access different fields it gives me an error. I try to log the type of one element of the JSON object to console. First it says Object and then it says undefines (or if try to log the content itself, it gives me an error).

var request = require('request');

const app = express();


 //For serving static pages
// app.use(express.static('./static'))
app.get('/', (req, res) =>{
    res.send('You have successfully contacted the API')
});

app.get('/:ticker', (req, res) => {
    var requestOptions = {
        'url': 'https://api.tiingo.com/tiingo/daily/' + req.params.ticker + '/prices?startDate=2019-01-02&token=74e7c9d22c2ffe8e9b5643edc2ef48bbddc6e69e',
        'headers': {
            'Content-Type': 'application/json'
            }
    };
    
    request(requestOptions,
        function(error, response, body) {
            result = JSON.parse(body);
            console.log('The type is ' + typeof (result[0].date)) //This statement prints different results twice
            res.send(result);
            
        }
    );   
});

app.listen(process.env.PORT || 3000)

Terminal says:

The type is string

D:\Web Dev Bootcamp\NodeJS-Tutorial\index.js:24
            console.log('The type is ' + typeof (result[0].date))
                                                           ^

TypeError: Cannot read property 'date' of undefined
    at Request._callback (D:\Web Dev Bootcamp\NodeJS-Tutorial\index.js:24:60)
    at Request.self.callback (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:185:22)
    at Request.emit (events.js:314:20)
    at Request.<anonymous> (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:1154:10)
    at Request.emit (events.js:314:20)
    at IncomingMessage.<anonymous> (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:1076:12)
    at Object.onceWrapper (events.js:420:28)
    at IncomingMessage.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1223:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) [nodemon] app crashed - waiting for file changes before starting...

Upvotes: 0

Views: 194

Answers (2)

Rizwan Malik
Rizwan Malik

Reputation: 21

Figured out what the issue was. Actually express was making a request for favicon.ico by itself and during that request apparently result variable was undefined. I simply set up another route for handling favicon request as suggested [here][1]. Now the code is simply logging the result once and I am able to access the fields of JSON object properly.

Edit: as pointed out by a contributor, its the browser thats making the favicon request and 'not' the express. [1]: Node Express "favicon.ico" not found error

Upvotes: -1

Harry Pretel
Harry Pretel

Reputation: 55

Run a quick console.log(result) to make sure that result is being stored as an Array. I suspect that when you are parsing the JSON it is storing result as an object.

Upvotes: 2

Related Questions