Day 5: Integrating Frontend with Backend

//Add axios library
yarn add axios

Create axiosConfig.js

import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:3000'
});

instance.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer SOME_TOKEN'; // For example purposes
  return config;
}, error => {
  return Promise.reject(error);
});

instance.interceptors.response.use(response => {
  return response;
}, error => {
  // Handle global error actions here
  return Promise.reject(error);
});

export default instance;

Modify api-be.js

// Modified GET endpoint for pagination
app.get('/items', async (req, res) => {
    // Use a default of 0 for page if not specified
    const page = req.query.page ? parseInt(req.query.page) : 0;

    // Use a default of 10 for limit if not specified
    const limit = req.query.limit ? parseInt(req.query.limit) : 10;

    try {
        const items = await Item.find().skip(page * limit).limit(limit);
        res.json(items);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

Create vue file ItemsCallFromAxios.vue

<template>
  <div>
    <ul>
      <li v-for="item in items" :key="item._id">
        {{ item.name }}
      </li>
    </ul>

    <!-- Pagination Controls -->
    <button @click="fetchItems(currentPage - 1)" :disabled="currentPage === 0">Previous</button>
    <button @click="fetchItems(currentPage + 1)">Next</button>
  </div>
</template>

<script>
import axios from './axiosConfig';

export default {
  data() {
    return {
      items: [],
      currentPage: 0
    };
  },
  created() {
    this.fetchItems(this.currentPage);
  },
  methods: {
    async fetchItems(page) {
      const response = await axios.get(`/items?page=${page}`);
      this.items = response.data;
      this.currentPage = page;
    }
  }
};
</script>

Modify router with previous file

import { createRouter, createWebHistory } from 'vue-router'
import HomeInit from '../views/HomeInit.vue'
import ProfileUser from '../views/ProfileUser.vue'
import ProductsItem from '../components/ProductsItem.vue';
import ShoppingCart from '../components/ShoppingCart.vue';
import DashboardWidget from '../components/DashboardWidget.vue'
import ItemsFromMongo from '../components/ItemsFromMongo.vue'
import ItemsCallFromAxios from '../components/ItemsCallFromAxios.vue' // Add Route

const routes = [
    {
        path: '/',
        name: 'HomeInit',
        component: HomeInit
    },
    {
        path: '/profile/:username',
        name: 'ProfileUser',
        component: ProfileUser,
        props: true
    },
    { path: '/products', component: ProductsItem },
    { path: '/cart', component: ShoppingCart },
    { path: '/dashboard', component: DashboardWidget },
    { path: '/items', component: ItemsFromMongo },
    { path: '/axios', component: ItemsCallFromAxios } //Add route
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

export default router

Add this line on App.vue

 <router-link to="/axios"> Call Items with axios</router-link>

if you have checkout exercise complete https://github.com/LeoReyesDev/vue-tutorial/tree/day05-sample

Post Comment