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

后端 未结 3 1391
悲哀的现实
悲哀的现实 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:27

    We can do it by mixins. Make a js file inside mixins folder and put this function there and add this mixin file in vue files to use this function.

    0 讨论(0)
  • 2021-01-22 10:46

    I used nuxt/axios.js for my nuxt app. You can use it as a plugin.

    In plugins folder, make a file axios.js

    import axios from 'axios'
    
    export default axios.create({
       baseURL: process.env.baseURL,
    })
    

    NOTE: I am storing the base url of the server to be called for APIs in environment variables using dotenv lib. And this way, the base url is set for all the calls to be made.

    Then import it in nuxt.config.js file:

    module.exports = {
    ....
    {
      modules: [
        '@nuxtjs/axios'
      ],
    
      axios: {
      ...
      },
    }
    

    TIP: If you have to store a value in axios like "token" or "cookie" globally. Then you can use axios defaults method

    axios.defaults.headers.common = { Authorization: `bearer ${token}` };
    
    0 讨论(0)
  • 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
     }

    0 讨论(0)
提交回复
热议问题