I'm working on my first CLI project and I'm having trouble getting it to execute API requests. I have tried fetch, axios, express, and a couple of npm packages, but I just can't figure out what's wrong. The project will console.log and gather user data from the command line, but will not retrieve API data. I'm using a fake API data url at this point just to be sure it works. Here is the code:
const axios = require('axios');
let apiResponse;
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
apiResponse = response;
console.log('Does this work?')
})
.catch(function (error) {
console.log(error, 'Error');
});
console.log('apiResponse: ', apiResponse);
In the command line I get 'apiResponse: undefined' when I run the file. Again, I've tried using several different libraries so I must be doing something fundamentally wrong. The console.log OUTSIDE of the function prints, but neither console.logs INSIDE are printing. Any help would be greatly appreciated!