vue-cli encapsulates axios

       Installation and proxy cross-domain will not be introduced here, you can check my other note Vue2 project architecture construction (6) - axios call interface, webpack proxy cross-domain configuration .

package request

       When encapsulating, I usually like to abstract the request into three files, and the file location is placed in src. As long as you can refer to it, there is no problem, as shown in the following figure:
write picture description here

fetch.js

import axios from 'axios' // 引入axios

export function fetch (options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({ // instance创建一个axios实例,可以自定义配置,可在 axios文档中查看详情
      // 所有的请求都会带上这些配置,比如全局都要用的身份信息等。
      headers: {
        'Content-Type': 'application/json'
        // 'token_in_header': global_.token,//token从全局变量那里传过来
      },
      timeout: 30 * 1000 // 30秒超时
    })
    instance(options)
      .then(response => { // then 请求成功之后进行什么操作
        resolve(response) // 把请求到的数据发到引用请求的地方
      })
      .catch(error => {
        console.log('请求异常信息:' + error)
        reject(error)
      })
  })
}

url.js

export default {
  Hallowmas: '/v2/movie/top250'
  // 接口代理配置
}

// 也可以像下面这样,区分环境或者区分服务器等等
// let service = 'dev';
// // let service = 'prod';
// let api = '';
// if (service === 'dev') {
//   /**dev开发**/
//   api = '/stomatology/patient';
// } else if (service === 'prod') {
//   /**prod部署**/
//   api = '/proxy/client';
// }
//
// export default {
//   /**个人中心start**/
//   //1 获取c端个人信息 POST /wx/getClientInfo
//   getClientInfo: `${api}/wx/getClientInfo`,
//   //2 获取手机注册验证码 POST /wx/getClientRegisterCode
//   getClientRegisterCode: `${api}/wx/getClientRegisterCode`,
//   //3 绑定手机号 POST /wx/clientBindMobile
//   clientBindMobile: `${api}/wx/clientBindMobile`,
//   /**个人中心end**/
//
// }

api.js

import { fetch } from './fetch'
import api from './url'

// 登录接口
export function lookOption () {
  return fetch({
    // api.Hallowmas 引用url.js里面的数据
    url: api.Hallowmas,
    method: 'get', // 请求方法
    params: {
      // currentUserId: userId // 传过去的参数
    }
  })
}

interface call

       Introduce the corresponding interface in the component that needs to call the interface. For example, the function of lookOption is defined in the api.js file. First introduce:

import { lookOption } from '../../axios/api'

       Then define the trigger of the function call, such as the created hook trigger

created () {
    lookOption(this.userInfo.userName, this.userInfo.userPassword).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }

This article is reproduced from OBKoro1: https://blog.csdn.net/OBKoro1/article/details/78450040?locationNum=4&fps=1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324893467&siteId=291194637