第一次尝试使用Node.js,我在理解如何导出要从中访问数据的对象时遇到了一些麻烦。
基本上,这里是一个名为scraper.js的文件,该文件可调用外部News API。在scraper.js中,我为EntertainmentArticles构建了一个类,以便可以从该类别返回的所有文章都可以通过EntertainmentArticles.articles访问。
class EntertainmentArticles {
constructor() {
this.articles = {}
}
}
在scraper.js文件的正下方,我对New API进行了调用,然后我想用获取的数据填充EntertainmentArticles.articles:
newsapi.v2.topHeadlines({
category: 'entertainment',
country: 'us'
}).then(async response => {
const entertainmentArticles = response
EntertainmentArticles.articles = entertainmentArticles
// console.log(EntertainmentArticles.articles)
}).catch(error =>
console.error(error.message)
)
然后我像这样导出类
module.exports = { EntertainmentArticles }
然后,我想将其导入另一个名为Articles.js的文件中,然后将其用于将文章持久保存到我的MongoDB数据库中。在articles.js的顶部,我有以下代码:
const entertainmentInstance = new EntertainmentArticles()
console.log(entertainmentInstance)
在控制台中,我看到它可以访问EntertainmentArticles类,但是articles是一个空对象,如下所示:
EntertainmentArticles { articles: {} }
在这种情况下,我很难弄清楚哪里出了问题,我可能是导出错误,还是没有将文章正确分配给EntertainmentArticles.articles?