简体   繁体   中英

Node js Empty object when executing a function from a required file

so i have this news api js file i can run and execute the api and see a full result when consoling

 const NewsAPI = require('newsapi'); const newsapi = new NewsAPI('2a59HIDDEN1bd60'); newsapi.v2.sources({ category: 'technology', language: 'en', country: 'us' }).then( response => { console.log(response) return response });

but when i require the above code in another file its coming as empty object

 const passport = require("passport"); const newsapiapi = require("../services/newsApi"); module.exports = (app) => { app.get( "/auth/google", passport.authenticate("google", { scope: ["profile", "email"], }) ); app.get("/auth/google/callback", passport.authenticate("google")); app.get('/api/current_user',(req,res)=>{ res.send(req.user); }) app.get('/api/newsapi',(req,res)=>{ var resp = newsapiapi console.log("-----------",resp) res.send("hello") }) };

In other words the object is empty when executing under app.get('/api/newsapi') but i get the data with no issue on the first code where the api lies

Because you are not exporting anything from the above file. add module.exports.

module.exports = newsapi.v2.sources({
        category: 'technology',
        language: 'en',
        country: 'us'
      }).then( response => {
      console.log(response)
        return response
      });

This is because you haven't exported anything from the api file. Try this

module.exports = newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });

This would export the function promise and then you can consume it by resolving it in the main file. Like

app.get('/api/newsapi', async (req,res)=>{
    var resp = await newsapiapi()
    console.log("-----------",resp)

    res.send("hello")

})

Or if you don't want to use async-await, you can use promise chaining like

app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi().then(resp => {
    console.log("-----------",resp) 
    res.send("hello")
   })

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM