Consuming API's

mtee

Margaret W.N

Posted on July 29, 2020

Consuming API's

I'd want to interact with my API from a webpage which creates the need to understand how to consume my API. I'll start by logging out the data on the console as I build up on rendering data as web content. I'll be using axios library to fetch data from the API. To begin with, I added and linked an index.html and index.js file. Then included the axios library.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

I also created a self invoking function in index.js and used async/await to await a promise.

(async () => {
  const response = await axios({
    url: 'http://localhost:4000/habittracker/habits',
    method: 'get'
  })
console.log(response);
})()
Enter fullscreen mode Exit fullscreen mode

This resulted in a CORS error.

Alt Text

To fix that I installed cors: npm install cors , included it in my app.js file and used it as middleware.

const cors = require('cors');
app.use(cors());
Enter fullscreen mode Exit fullscreen mode

Data is now logged out to the console:

Alt Text

There's a lot of meta data in the console that I'm not interested with at the moment; to retrieve an array of habits only, I'll update the response in console.log with:

console.log(response.data);
Enter fullscreen mode Exit fullscreen mode

This leaves me with just habits on the console:

Alt Text

That's it for Day 13

πŸ’– πŸ’ͺ πŸ™… 🚩
mtee
Margaret W.N

Posted on July 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 23 of 100DaysOfCode
javascript Day 23 of 100DaysOfCode

October 3, 2024

Day21 of 100DaysOfCode
javascript Day21 of 100DaysOfCode

August 22, 2024

Day22 of 100DaysOfCode
javascript Day22 of 100DaysOfCode

September 7, 2024

Day 2 of #100daysofMiva Coding Challenge
100daysofmiva Day 2 of #100daysofMiva Coding Challenge

August 22, 2024