Vue cli project template file description asynchronous request

Posted by sheen4him on Tue, 19 Nov 2019 20:25:04 +0100

This article is the http part of src directory under vue/cli, with project structure reference Description of Vue cli project template file (I) overall structure

Reference to this catalog Here If you have any questions about this directory, you can adjust it by reference. The following is the contents of a single file
(1) config.js

export default {
  method: 'post',
  //Base path prefix, if there are multiple, can be set separately in the request
  baseURL: 'https://cnodejs.org/api/',
  // Request header information. It is recommended to make an agreement with the server students
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  // parameter
  data: {},
  // Set timeout
  timeout: 3000,
  // Carry credentials
  withCredentials: true,
  // Return data type
  responseType: 'json'
}

(2)api.js

import axios from 'axios'   // Here, you need to install axios before importing
import config from '@/http/config.js' //Import profile
import qs from 'qs' // Serialize request data, see server requirements
import Vue from 'vue'  //This import and the next import are to apply the prompt function of the vux UI framework, which can be modified by referring to its own project framework
import { ToastPlugin } from 'vux' // Introducing prompt function from vux

Vue.use(ToastPlugin, {position: 'middle'}) // Setup and mount the VX prompt function
export default function $axios (options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: config.baseURL,
      headers: config.headers,
      transformResponse: [function (data) {}]
    })
    // request interceptor
    instance.interceptors.request.use(
      config => {
        // Tip: 1
        // At the beginning of the request, the full screen loading animation can be started in combination with the vuex

        // Tip: 2
        // With token, it can be combined with vuex or heavy localStorage
        // if (store.getters.token) {
        //     config.headers['X-Token'] = getToken() / / make each request carry token--['X-Token'] as a custom key. Please modify it according to the actual situation
        // } else {
        // Redirect to login page
        // }
        // Tip: 3
        // According to the request method, serialize the parameters sent, and whether to serialize according to the requirements of the server
        if (config.method.toLocaleLowerCase() === 'put' ||
            config.method.toLocaleLowerCase() === 'delete') {
          config.data = qs.stringify(config.data)
        }
        if (config.method.toLocaleLowerCase() === 'post') {
          config.data = {...config.data, static_req: 'lyww1992'} // Here, to set the string required for each request... Operators can refer to ES6 by themselves
          config.data = qs.stringify(config.data)
          console.log(config.data)
        }
        return config
      },
      error => {
        // Do something when requesting an error (interface error, timeout, etc.)
        // Tip: 4
        // Turn off loading
        console.log('request:', error)

        // Judge request timeout
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          console.log('According to your settings timeout/Real request timeout judge request timeout now, you can add timeout processing scheme here')
          // return service.request(originalRequest); / / for example, repeat the request again
        }
        return Promise.reject(error) // You can get the error information you want to return at the call side
      }
    )

    // response interceptor
    instance.interceptors.response.use(
      response => {
        console.log(response)
        let texturl = response.config.url
        let data
        // When IE9, response.data is undefined, so you need to use response.request.responsetext (string after stringify
        if (response.data === undefined) {
          data = response.request.responseText     
        } else {
          data = response.data
        }
        data = JSON.parse(data) // This line processes all return strings to json format by default. If there is any difference, please delete this line of code and convert it separately when using
        // Do different processing according to the returned code value (as agreed with the server)
        switch (data.errorno) {
          case '200':
            break
          default:
        }
        return data
      },
      err => {
        if (err && err.response) {
          switch (err.response.status) {
            case 400:
              err.message = 'Request error'
              break

            case 401:
              err.message = 'Unauthorized, please log in'
              break

            case 403:
              err.message = 'access denied'
              break

            case 404:
              err.message = `Error requesting address: ${err.response.config.url}`
              break

            case 408:
              err.message = 'request timeout'
              break

            case 500:
              err.message = 'Server internal error'
              break

            case 501:
              err.message = 'Service not implemented'
              break

            case 502:
              err.message = 'Bad Gateway'
              break

            case 503:
              err.message = 'Service not available'
              break

            case 504:
              err.message = 'gateway timeout'
              break

            case 505:
              err.message = 'HTTP Version not supported'
              break

            default:
          }
        }
        console.error(err)
        /*  This part is the application of vux prompt component
        this.$vux.toast.show({
          text: err,
          time: 800,
          width: '3.75rem'
        })
        */
        return Promise.reject(err) // Returns the error information returned by the interface
      }
    )

    // Request processing
    instance(options)
      .then((res) => {
        resolve(res)
        return false
      })
      .catch((error) => {
        reject(error)
      })
  })
}

(3) interface.js
This part is the unified management directory of all API interfaces cnode.js API provided)
Briefly describe this part
a. request type and parameters
Parameter setting is params when get request and data when post request!!!
Parameter setting is params when get request and data when post request!!!
Parameter setting is params when get request and data when post request!!!
No reason. According to the official regulations of axios, please refer to other types of requests axios Chinese document
b. if there are different sources in the interface part, such as getText in the example, its request is different from other interfaces, and there are multiple sources, so it is recommended to configure the url separately (the URLs in this example are all proxyTable agents through config/index.js, please refer to my another blog for this part Parsing and proxyTable configuration in index.js under Vue cli config)

import axios from '@/http/api' // Import api

// Separate export
// Theme home page
export const getTopicHome = params => {
  return axios({
    url: '/api/v1/topics',
    method: 'get',
    params
  })
}
// Theme details
export const getTopicDetail = params => {
  return axios({
    url: '/api/v1/topic',
    method: 'get',
    params
  })
}
// Theme collection
export const topicCollect= data => {
  return axios({
    url: '/api/v1/topic_collect/collect',
    method: 'post',
    data
  })
}
// Cancel theme
export const deleteCollect = data => {
  return axios({
    url: '/api/v1/topic_collect/de_collect',
    method: 'post',
    data
  })
}

// When another interface is requested and the interface itself has multiple sources
export const getText = (textlocal, singleUrl, params) => {
  let pro
  if (textlocal.match(/dwtxt/)) {
    pro = '/resource1'
  }
  if (textlocal === 'upld.17k.ren') {
    pro = '/resource2'
  }
  return axios({
    url: pro + singleUrl,
    method: 'get',
    params
  })
}

// Default rewind all
export default {
  getTopicHome,
  getTopicDetail,
  topicCollect,
  deleteCollect,
  getText
}

(4). index.js

// Import all interfaces
import apiList from '@/http/interface'

const install = Vue => {
  if (install.installed) {
    return
  }
  install.installed = true

  Object.defineProperties(Vue.prototype, {
    // This is mounted on the $api object of the Vue prototype
    $api: {
      get () {
        return apiList
      }
    }
  })
}

export default install

(5) instructions
Mount in main.js

import api from '@/http/index' // Asynchronous request

Invoke in *.vue file

// Call topic Homepage
this.$api.getTopicHome()
.then(data => {
consoel.log(data) // This is the callback data after the request succeeds
})
.catch(() => {
console.log('Request error')
})
//Call theme collection
this.$api.topicCollect({topic_id: 5433d5e4e737cbe96dcef312})
.then(data => {
consoel.log(data) // This is the callback data after the request succeeds
})
.catch(() => {
console.log('Request error')
})

Topics: axios Vue JSON