DEV Community

Margaret W.N
Margaret W.N

Posted on

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

Top comments (0)