[Fixed] How to move axios instance around in project

Issue

I am working with Axios in a express.js / node.js project and I am trying to pass around an Axios instance.

The thing that confuses me is how things get passed around in javascript and many things aren’t really happening sequentially code wise. Could someone direct me to the proper way of achieving this?
Currently I am requesting a token from Spotify’s API and then using that to create an Axios instance to make further calls to Spotify.

spotify-auth.js

const axios = require('axios').default;
let config = require('../../config');

var spotifyAxios = undefined;
console.log('this isnt logging');

axios.request({
    url: "/api/token",
    method: "post",
    baseURL: "https://accounts.spotify.com/",
    auth: {
        username: config.spotify_client_id,
        password: config.spotify_client_secret,
    },
    params: {
        "grant_type": "client_credentials",
    },
    headers: {
        "Accept": 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}).then(res => {
    console.log(res.data);
    try {
        var token = res.data.access_token;
        spotifyAxios = axios.create({
            baseURL: 'https://api.spotify.com/v1/',
            timeout: 1200,
            headers: {'Authorization': 'Bearer'+token}
        });
        console.log("spotifyAxios created");
    }
    catch(err) {
        console.log(err);
        spotifyAxios = undefined;
    }
    
}, (err) => {
    console.log(err);
});

console.log('this isnt logging')
module.exports = spotifyAxios;

spotify.controller.js

const axios = require('axios').default;
const spotifyAxios = require('../services/spotify-auth');

exports.searchAlbum = function(req, res) {
    console.log(req.params);
    if (req.params.album == undefined) {
        res.status(400).send("searching string undefined");
        return;
    }

    try {
        spotifyAxios.request({
            method: 'get',
            url: 'https://api.spotify.com/v1/search',
            data: {
                q: req.params.album,
                type: "album",
            }
        }).then(res => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });
    }
    catch(err) {
        console.log(err); // making the API call leads to error here because spotifyAxios isn't defined (undefined)
        res.status(500).send("unable to search albums");
    }    
}

Solution

Try this , i think because API call is Asycronus

spotify-auth.js

const axios = require('axios').default;
let config = require('../../config');

//var spotifyAxios = undefined;
console.log('this isnt logging');
async function spotifyAxios() {
    await axios.request({
        url: "/api/token",
        method: "post",
        baseURL: "https://accounts.spotify.com/",
        auth: {
            username: config.spotify_client_id,
            password: config.spotify_client_secret,
        },
        params: {
            "grant_type": "client_credentials",
        },
        headers: {
            "Accept": 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    }).then(async res => {
        console.log(res.data);
        try {
            var token = res.data.access_token;
            return await axios.create({
                baseURL: 'https://api.spotify.com/v1/',
                timeout: 1200,
                headers: {'Authorization': 'Bearer'+token}
            });
            console.log("spotifyAxios created");
        }
        catch(err) {
            console.log(err);
            spotifyAxios = undefined;
        }
    
    }, (err) => {
        console.log(err);
    });
}

console.log('this isnt logging')
module.exports = spotifyAxios;

spotify.controller.js

const axios = require('axios').default;
const spotifyAxios = require('../services/spotify-auth');

exports.searchAlbum = async function(req, res) {
    console.log(req.params);
    if (req.params.album == undefined) {
        res.status(400).send("searching string undefined");
        return;
    }

    try {
        await spotifyAxios.request({
            method: 'get',
            url: 'https://api.spotify.com/v1/search',
            data: {
                q: req.params.album,
                type: "album",
            }
        }).then(res => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });
    }
    catch(err) {
        console.log(err); // making the API call leads to error here because spotifyAxios isn't defined (undefined)
        res.status(500).send("unable to search albums");
    }    
}

Leave a Reply

(*) Required, Your email will not be published