How to avoid code duplication when running NUXT.js and Axios?

后端 未结 3 1390
悲哀的现实
悲哀的现实 2021-01-22 10:25

If similar code (as in the example) is duplicated in different components but with slight differences in the name of what I pass in the function parameters

What a

3条回答
  •  借酒劲吻你
    2021-01-22 10:47

    For axios calls, you can create a function or class and import it every time

    Something like services/axios

    import axios from 'axios';
    
    
    const axiosInstance = axios.create({
        baseURL: process.env.VUE_APP_BASE_URL,
        headers: {
            'Access-Control-Allow-Origin': '*',
            accept: 'Accept: application/json',
        },
    });
    
    export default axiosInstance;

    And then in utils/requests

    import axiosInstance from '@/services/axios';
    
    const apiRequest = async (axiosConfig) => {
      try {
          const response = await axiosInstance(axiosConfig);
          return {
            success: true,
            data: response.data.data || response.data;
          }
      } catch (error) {
          if (error.response) {
           error = error.response
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
           error = error.request
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          console.log(error.request);
        } else {
           error = error.message
          // Something happened in setting up the request that triggered an Error
          console.log('Error', error.message);
        }
          return {
            success: false,
            error
          }
      }
    };
    
    export const getRequest = async (url) =>
        await apiRequest({
            method: 'GET',
            url,
        });
    
    export const postRequest = async(url, requestBody) =>
        await apiRequest({
            method: 'POST',
            url,
            data: requestBody
        });

    You then import the getRequest and postRequest methods in the components

    component.vue

    import { getRequest, postRequest } from '@/utils/requests';
    
     
    const response = await postRequest('/url', requestBody);
     
    if (response.success) {
       // do stuff on success
     } else {
      // error message
     }

提交回复
热议问题