Good morning all! I am having issues getting an axios response back from a different function. Specifically, I am consulting a service I created in a different website and have it return a database name. Currently, as I call the api directly with it's headers on Postman it works and the same when it is done inside the getDbName() function I created using axios, however when I try to return that response into another one, it prints out "undefined". It was my understanding that as long as the response => arrow functions are used, the call would await the response properly. Am I wrong on that assumption?
I've tried many different attempts of returning the variable. I investigated using the many links on SO below, but I still couldn't get it to work:
axios promise returns correct value in "axios.all" function, but is undefined in the "then" function
Axios prints value on console but returns undefined
GET request with axios returning undefined
[dbController.js]
import axios from 'axios';
import apiconfig from '../config/apiconfig';
function getDbName() {
return axios({
method: 'GET',
url: `${apiconfig.cb_url}/api/DbToBeWorked`,
headers: apiconfig.optionsHeaders,
}).then(dbn => {
console.log(dbn.data.db); //logs database name correctly
return dbn.data.db;
});
};
[routes.js]
import { Router } from 'express';
const routes = new Router();
routes.get('/api/test', (req, res) => {
getDbName().then(dbn => {
console.log(dbn) //this logs 'undefined'
return res.status(200).json(dbn);
});
});
The output should be dbn (database name) for both console.logs. At the moment, one returns the correct name and the other returns undefined.