api请求模块化,让你的接口变得更加优雅

1、新建一个js写入( 假设文件名叫demo.js

import http from '../assets/http'
export function demo (data) {
  return http({
    method: 'post',
    url: 'api/api/admin/loockinfoApply',
    data
  })
}

2、去单页面那进行引入

import {demo} from './demo.js'
export default {
  name: 'App',
  async created () {
    console.log(await demo({id: 1}))
  }
}

之后的请求就可以照葫芦画瓢

export function demo (data) {
  return http({
    method: 'post',
    url: 'api/api/admin/loockinfoApply1',
    data
  })
}

export function demo1 (data) {
  return http({
    method: 'post',
    url: 'api/api/admin/loockinfoApply2',
    data
  })
}

export function demo2 (data) {
  return http({
    method: 'post',
    url: 'api/api/admin/loockinfoApply3',
    data
  })
}
import {demo, demo1, demo2} from './demo.js'
export default {
  name: 'App',
  async created () {
    console.log(await demo({id: 1}))
    console.log(await demo1({id: 1}))
    console.log(await demo2({id: 1}))
  }
}

http.js

import axios from 'axios'
import Cookies from 'js-cookie'
const http = options => {
  return new Promise((resolve, reject) => {
    const defaultOptions = {}
    const newOptions = {
      ...defaultOptions,
      ...options
    }
    newOptions.headers = {
      'content-Type': 'application/json;charset=UTF-8',
      'token': Cookies.get('zhelicooke'),
      ...newOptions.headers
    }
    // console.log(newOptions);
    axios({
      method: newOptions.method,
      url: newOptions.url,
      data: newOptions.data,
      headers: newOptions.headers
    }).then(res => {
      if (res.status === 200) {
        resolve(res.data)
      } else {
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

export default http

你可能感兴趣的:(api请求模块化,让你的接口变得更加优雅)