我有一个类的方法,应该给我一个API的域。到目前为止,这也有效。但是如果我想用Node Express渲染它,我得到一个1.2.3的数组。没有域名。
我认为我的问题位于async等待?!
这是我的类方法的片段:
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);
}
}
而她是我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
});
});
};
使用push(域),我只能在HTML页面上获得1.2.3。
这与我的API的三个活动域完全对应。但只是没有域名。 :(
但是如果我输入for loop console.log(response [i] ['domain']。domains)我会在控制台中获得所有名称的域名。
有谁看到我的错误?
这是我的解决方案:
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
});
}
};
尝试使您的路由异步如下:
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
});
}
};