I have a class with methods which should give me domains of an API. That also works so far. But if I want to render it with Node Express I get an array with 1.2.3. without the domain name.
I think my problem is located at async await?!
Here is a snippet from my class method:
class ISPConfig {
constructor(base_url, options) {
this.base_url = base_url;
this.options = options;
}
async _call() {
... // gives me the sessionId
}
async getDataByPrimaryId(ispFunction, param) {
try {
const results = await axios.post(this.base_url + ispFunction, {
session_id: await this._call(),
primary_id: param
});
return await results.data.response;
//console.log(results.data.response);
} catch (err){
console.log(err);
}
}
And her a snippet from my app.js:
const renderHome = (req, res) => {
let domains = [],
message = '';
let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS)
a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' })
.then(response => {
for (let i = 0; i < response.length; i++){
domains = response[i]['domain'].domains;
}
})
.catch(err => {
message = 'Error when retriving domains from ISPApi';
})
.then(() => {
res.render('home', { // 'home' template file for output render
title: 'ISPConfig',
heading: 'Welcome to my ISPConfig Dashboard',
homeActive: true,
domains,
message
});
});
};
With push(domains) I get on the HTML page only 1.2.3.
Which corresponds exactly to the three active domains of my API. But just without the domain names. :(
But if I output in for loop console.log(response[i]['domain'].domains) I get all domains with names in console.
Does anyone see my mistake?
Here is my Solution:
const renderHome = async (req, res) => {
let domain = [],
message = '';
try {
let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS);
const response = await a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' });
for (let i = 0; i < response.length; i++){
domain.push(response[i].domain);
}
} catch(err) {
message = 'Error when retriving domains from ISPApi';
} finally {
res.render('home', { // 'home' template file for output render
title: 'ISPConfig',
heading: 'Welcome to my ISPConfig Dashboard',
homeActive: true,
domain,
message
});
}
};
Try making your route async too like:
const renderHome = async (req, res) => {
let domains = [],
message = '';
try {
let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS)
const response = await a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' })
for (let i = 0; i < response.length; i++){
domains.push(response[i].domain);
}
} catch(err) {
message = 'Error when retriving domains from ISPApi';
} finally {
res.render('home', { // 'home' template file for output render
title: 'ISPConfig',
heading: 'Welcome to my ISPConfig Dashboard',
homeActive: true,
domains,
message
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With