Front-end frameworks are popping up all the time. The size of the project varies, and for small projects there is no file structure. For most projects we need to do the following

  • Standardize the file catalog and improve the project structure to achieve clear thinking during development, accurate error positioning and convenient maintenance

So we all need to be prepared with a framework that fits our development habits in order to improve the efficiency of our next development. Here to vuE-CLI + AXIOS as an example to improve our API interface management.

  1. Creating projects, installing vue-CLI, Axios, etc
  2. Encapsulate the AXIOS file for unified handling of the request responseThis file is usually in the framework util file,utils/request.js
import axios from 'axios'
import store from '@/store'
import {Toast,Notify} from 'Own UI library'
// Introduce different API addresses according to the environment (you can write different files to distinguish the environment)
import {baseApi} from '@/config'
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  timeout:6000.// request timeout
})

// Set the default post and GET content-type
service.defaults.headers.post['Content-Type'] = 'application/json'
service.defaults.headers.get['Content-Type'] = 'application/json'


// Request interceptor
service.interceptors.request.use(
  config= > {
    // Do not enable loading by default
    if(! config.hideloading) {// loading
      Toast.loading({
        forbidClick: true})}if (store.getters.token) {
      config.headers['X-Token'] = ' '
    }
    return config
  },
  error= > {
    console.log(error) // for debug
    Toast.fail('Request error, please try again');
    return Promise.reject(error)
  }
)
// Respone interceptor
service.interceptors.response.use(
  response= > {
    Toast.clear()
    const res = response
    if(res.status && res.status ! = =200) {
      // Login timed out. Log in again
      if (res.status === 401) {
        store.dispatch('FedLogOut').then(() = > {
          location.reload()
        })
      }
      return Promise.reject(res.data || 'error')}else {
      if(res.data.status === 'failed'){
        Toast.fail(res.data.message);
      };
      return Promise.resolve(res.data)
    }
  },
  error= > {
    Toast.clear()
    Toast.fail('Network error');
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service

Copy the code

2. In the second step, we create an API folder in the SRC directory for different API management. Get. Post requests can be wrapped in index.js first, or elsewhere

// Request method encapsulation
import axios from '@/utils/request'


/** * encapsulates the get method *@param url
 * @param data
 * @returns {Promise}* /
export function get(url, params = {}) {
    return new Promise((resolve, reject) = > {
      axios
        .get(url, {
          params: params
        })
        .then(response= > {
           resolve(response);
        })
        .catch(err= > {
          reject(err);
        });
    });
  }


  /** * encapsulates the POST request *@param url
 * @param data
 * @returns {Promise}* /
export function post(url, data = {}) {
    return new Promise((resolve, reject) = > {
      axios.post(url, data).then(
        response= > {
          resolve(response);
        },
        err= >{ reject(err); }); }); }Copy the code
  1. You are ready to write the interface file

src/api/user.js

// axios
import request from '@/utils/request'
//user api

/ / login
export function login(params) {
  return request({
    url: '/login'.method: 'post'.data: params
  })
}

/ / register
export function register(params) {
  return request({
    url: '/register'.method: 'post'.data: params
  })
}
Copy the code

This is where our API file planning is basically done. We just need to introduce the feature of import deconstruction where the interface needs to be called

<! -- home --><template>
  <div class="app-container">
       login
  </div>
</template>

<script>
import {login} from '@/api/user'
export default {
  data() {
    return {
      userForm: {
        a: ' '.b: ' '}}},methods: {
    onSubmit() {
      login(this.userForm)
        .then(res= > {
          console.log(res)
        })
        .catch(err= > {
          console.log(err,'wrong')})}},created(){}}</script>
</style>

Copy the code

Our project catalog ended up looking something like this!