loading...

Consuming API's

mtee profile image Margaret W.N ・1 min read

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>

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);
})()

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());

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);

This leaves me with just habits on the console:

Alt Text

That's it for Day 13

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide