Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] 使用vue开发过程你是怎么做接口管理的? #306

Open
haizhilin2013 opened this issue Jun 20, 2019 · 4 comments
Open

[vue] 使用vue开发过程你是怎么做接口管理的? #306

haizhilin2013 opened this issue Jun 20, 2019 · 4 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] 使用vue开发过程你是怎么做接口管理的?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@Sihan-Tan
Copy link

在request.js中对 axios 请求 和 响应进行劫持,统一处理,然后在 api 文件夹中引入 request.js 后再使用 封装后的方法进行请求

@canwdev
Copy link

canwdev commented May 18, 2020

创建一个request.js用于封装axios,在 src/api/request,设置拦截器统一处理请求和相应。

封装 axios:request.js

import axios from 'axios'
import {Message, Loading} from "element-ui"
import {getToken} from "@/utils/auth"

function Index({...config}) {
  // create an axios instance
  const service = axios.create({
    /*headers: {
      'Cache-Control': 'no-cache'
    },*/
    baseURL: config.baseURL || process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000 // request timeout
  })

  // request interceptor
  service.interceptors.request.use(
    config => {
      return config
    },
    error => {
      return Promise.reject(error)
    }
  )

  // response interceptor
  service.interceptors.response.use(
    response => {
      return response
    },
    error => {
      const {request = {}} = error;
      const {status, response} = request;

      error.status = status
      try {
        error.res = JSON.parse(response)
      } catch (e) {
        console.warn(e)
      }
      return Promise.reject(error)
    }
  )

  /**
   * 发起请求
   * @param method 请求方法
   * @param url 请求地址
   * @param params 要发送的数据
   * @param config 配置
   * @param axiosConfig Axios配置项
   * @returns {Promise<never>|Promise<AxiosResponse<T>>}
   */
  const requestProcessor = (method, url, params, config, axiosConfig) => {
    const headers = {}
    const token = getToken().token
    if (token) {
      // let each request carry token
      headers['Authorization'] = 'JWT ' + token
    }

    if (config.formData) {
      const fd = new FormData();
      for (let key in params) {
        fd.append(key, params[key])
      }
      params = fd
    }

    switch (method.toUpperCase()) {
      case 'GET':
        return service.get(url, {
          params,
          headers,
          ...axiosConfig,
        })
      case 'POST':
        return service.post(url, params, {
          headers,
          ...axiosConfig,
        })
      case 'DELETE':
        return service.delete(url, {
          params,
          headers,
          ...axiosConfig,
        })
      case 'PUT':
        return service.put(url, params, {
          headers,
          ...axiosConfig,
        })
      default:
        return Promise.reject(new Error(`${method} 方法无效,请用正确的请求方法`))
    }
  }

  this.service = async ({method, url, params, config = {}, axiosConfig = {}}) => {
    const {isLoading = true, isToast = true} = config

    let loadingInstance
    isLoading && (loadingInstance = Loading.service({
      fullscreen: true,
      background: 'transparent',
      text: '加载中...'
    }))

    try {
      const response = await requestProcessor(method, url, params, config, axiosConfig)
      // 此处可以再次拦截
      return response.data
    } catch (error) {
      isToast && Message.error(error.message)
      throw error
    } finally {
      isLoading && loadingInstance.close()
    }

  }
}

export const {request} = new Index()
export default Index

接口 listing.js

import Request from "@/api/request"

const {service} = new Request()

export default {
  userPostList({pageSize, page}) {
    return service({
      method: 'get',
      url: '/userpostlist/',
      params: {
        pageSize,
        page
      },
      config: {
        isLoading: false
      }
    })
  }
}

在 Vue 组件中使用:

import listing from "@/api/listing"

export default {
    mounted() {
      this.getList()
    },
    methods: {
      getList() {
        this.isLoading = true

        listing.userPostList({
          pageSize: this.pageSize,
          page: this.currentPage,
        }).then(data => {
          this.currentPage = parseInt(data.currentPage)
          this.total = data.total
          this.list = data.results

        }).finally(() => {
          this.isLoading = false
        })
      }
    }
}

@crush2020
Copy link

对接口做统一的封装管理

@Cai-zhiji
Copy link

Vue开发过程中如何做接口管理

手动管理

最简单的方式是手动创建一个文件或目录,用于存放所有的接口请求函数。可以根据模块或功能将接口进行分类,每个接口对应一个函数,函数中使用Axios或其他HTTP库发送请求。

// api/user.js
import axios from 'axios';

export function getUser(id) {
  return axios.get(`/api/user/${id}`);
}

// api/product.js
import axios from 'axios';

export function getProduct(id) {
  return axios.get(`/api/product/${id}`);
}

这种方式简单直观,适用于小型项目或接口较少的情况,但随着项目规模增大,接口增多,手动管理可能变得不够便捷。

使用接口管理工具:

可以使用专门的接口管理工具来管理接口。这些工具提供了接口定义、自动生成请求函数、接口文档等功能,可以更方便地管理和维护接口。
示例:
Swagger:一个流行的开源工具,用于设计、构建和文档化RESTful API。
Postman:一个功能强大的API测试和开发工具,提供接口管理和文档化功能。
Rap2:一个可视化的接口管理工具,支持接口定义、Mock数据、接口测试等功能。
使用接口管理工具可以提高开发效率和团队协作,保持接口定义的一致性,并提供方便的接口文档和调试工具。

使用插件或库:

有一些专门的插件或库可以用于管理接口,例如vue-axios、@nuxtjs/axios等。这些插件提供了在Vue中集成Axios的便捷方式,并支持配置和管理接口。

示例(使用vue-axios):

// main.js
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);

// api/user.js
import Vue from 'vue';

export function getUser(id) {
  return Vue.axios.get(`/api/user/${id}`);
}

使用插件或库可以简化接口的配置和调用,并提供一些额外的功能,如拦截器、全局配置等。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

5 participants