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...
result[0]isundefinedso thenresult[0].dateis a TypeError. You will have to either figure out why that is or check to see ifresultandresult[0]are valid before you try to use them. Since you are varyingreq.params.tickerfrom one request to the next, perhaps it doesn't work for some ticker values.console.log(req.params.ticker)to your request handler as you are probably getting a value you do not want. For example, if this was coming from a browser, you may be gettingfavicon.icobecause yourapp.get('/:ticker', ...)is a wildcard route that matches any top level request that is sent to your server. This is often problematic.