How can i export API responses using modules to another JS file?

Viewed 24

I am trying to export API responses from one JS file and import it to another file, but it is showing me an error:

GET http://127.0.0.1:5500/js/api_responses net::ERR_ABORTED 404 (Not Found)

This is the API response file:

let response

async function getData() {
    try {
        response = await fetch(`https://newsapi.org/v2/top-headlines?country=in&apiKey=${API_KEY.appID}`)
        response = await response.json()
        return response
    } catch (err) {
        return 'error'
    }
}

// readTime 
const readTime = (response) => {
    const indexOfPlus = response.articles[0].content.indexOf('+')

    const charEndPoint = response.articles[0].content.indexOf(" ", indexOfPlus + 1)

    return Math.ceil(((parseInt(response.articles[0].content.slice(indexOfPlus + 1, charEndPoint), 10) + 100) / 4) / 200)
}

let estimatedReadingTime = readTime()

export { estimatedReadingTime }

Importing File:

import { estimatedReadingTime } from "./api_responses"
console.log(estimatedReadingTime)
1 Answers

You split code but didn't connect it really. This block should work.



async function getData() { // this function already returns a value. we don't need a global variable to update all the time
    try {
     let response = await fetch(`https://newsapi.org/v2/top-headlines?country=in&apiKey=${API_KEY.appID}`)
       const parsedResponse = await response.json()
          return parsedResponse;
    } catch (err) {
        return 'error'
    }
}

// readTime 
 const readTime = async () => {
      const response = await getData(); // now we get the data if api call
      // below here your logic runs as usual
    const indexOfPlus = response.articles[0].content.indexOf('+')

    const charEndPoint = response.articles[0].content.indexOf(" ", indexOfPlus + 1)

    return Math.ceil(((parseInt(response.articles[0].content.slice(indexOfPlus + 1, charEndPoint), 10) + 100) / 4) / 200)
}
// now when you call readTime function in another file, you will have the results that we create in here

module.exports = readTime;
Related