【问题标题】:How to avoid code duplication when running NUXT.js and Axios?NUXT.js 和 Axios 运行时如何避免代码重复?
【发布时间】:2020-11-22 05:28:43
【问题描述】:

如果相似的代码(如示例中)在不同的组件中重复,但我在函数参数中传递的名称略有不同

有哪些选项可以将代码单独放在某个地方,然后使用自定义参数将其引入我的组件中? (每个组件单独)

我应该通过插件来做到这一点吗? 如果是这样,那么我如何在组件上实现单独的必要参数+如何仅在这些组件上连接插件而不在其他地方连接?

【问题讨论】:

  • 你不需要这样做,因为每个请求都是不同的,最重要的是,当请求成功或失败时你会做其他事情

标签: javascript vue.js axios nuxt.js


【解决方案1】:

对于axios调用,可以创建一个函数或者类,每次都导入

类似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;

然后在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
    });

然后在组件中导入 getRequest 和 postRequest 方法

component.vue

import { getRequest, postRequest } from '@/utils/requests';

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

【讨论】:

    【解决方案2】:

    我们可以通过 mixins 来实现。在 mixins 文件夹中创建一个 js 文件并将这个函数放在那里,并将这个 mixin 文件添加到 vue 文件中以使用这个函数。

    【讨论】:

      【解决方案3】:

      我在我的 nuxt 应用程序中使用了 nuxt/axios.js。您可以将其用作插件。

      在插件文件夹中,创建一个文件axios.js

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

      注意:我使用dotenv lib 将要为API 调用的服务器的基本URL 存储在环境变量中。这样,就为所有要进行的调用设置了基本 url。

      然后在nuxt.config.js文件中导入:

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

      提示:如果您必须在 axios 中全局存储一个值,例如“token”或“cookie”。然后就可以使用axiosdefaults方法

      axios.defaults.headers.common = { Authorization: `bearer ${token}` };
      

      【讨论】:

        猜你喜欢
        • 2011-08-29
        • 1970-01-01
        • 2021-04-28
        • 2018-08-16
        • 2014-03-07
        • 2015-12-29
        相关资源
        最近更新 更多