Requirements describe

When doing the vue program, we often encounter a problem’s request we need to add a request header, or is not a request header, so that we can use the primitive way, when we write directly directly and request header, so that you can avoid the late and not on the situation, but there are two things we are helpless, The first is to change the request header information, the second is the beginning of the without, but asked us to add behind, in both cases if we request less time was acceptable, but if more time is sick, estimate the dead heart have, also is our version of the iteration, domain name will be combined with the corresponding middle version number, This time if one by one to write, estimated also enough to make a headache, and so on, are in the interface name to do the article, then we request encapsulation is particularly important. So in fact, if we do not encapsulate the request in the early stage, it can also be unified configuration, but this is the only way to unified configuration request information

The code analysis
Look at directory structure

request.js
import axios from 'axios'
import {Toast,Indicator} from 'mint-ui';

function checkStatus (response) {
  if (response.status === 200) {
    return response
  } else {
    console.log(response)
  }
}
// Common request header
function requestHeader (opt) {
  let myHeaders = opt.headers;
  if(! myHeaders) { myHeaders = {}; myHeaders['Content-Type'] = "application/json; charset=utf-8";
  }
  myHeaders['authorization'] = sessionStorage.getItem('authorization');
  return myHeaders
}
// Encapsulate the request body
export function request (options) {
  return axios({
    method: options.method,
    url: options.url,
    data: options.data,
    params:options.params,
    headers: requestHeader(options),
  })
    .then(checkStatus)
    .then(res= > {
      if (options.method.toUpperCase() === 'HEAD') {
        return {success: true}}else {
        if(res.status === 200) {return res.data
        }else{
          Toast(res.statusText)
        }
      }
    }).catch(function (err){
      if (options.method.toUpperCase() === 'HEAD') {
        return {success: false}}else {
        Toast(Background processing is abnormal. Please try again later.); }}); }Copy the code

This file is a wrapper around the axios request, and the comments above are clear, so I don’t want to comment too much here.

Constants.js
export default {
  / / host_login: 'http://www.crowncrystalhotel.com:9519', / / offline simulation landing interface IP
  / / host_submit: 'http://47.98.113.173:9104', / / offline cleaning tasks
  host_login:'http://47.98.113.173:9022'.// The IP address of the interface for simulating login
  host_submit:'http://service.crowncrystalhotel.com'.// Online public account cleaning task
}
Copy the code

This file is unified configuration domain information, in fact, we usually only one this domain name, so here it is ok to write a directly, just my project, I here will have a lot of domain name, because the backend is more, the service is different, so here we write their own suitable code depending on the situation.

Config.js
module.exports = {
  api : {
     "clean_employee_login":'/v1/common/employee/login'.// Do authorization, simulate login
     "clean_task_api" : '/v1/room_service/add_sweep/'.// Clean interface
  },
  roles: {},authors: {}};Copy the code

The file here is the name of the interface, generally a domain name corresponds to the name of many interfaces, so no matter whether there are multiple in the previous file, here is generally not a file, because a project does not have only one interface, here is not to repeat, take a look at the writing of the file.

Vue file reference
import data from '.. /.. /utils/date'; Js import {API} from '.. /.. /utils/Config' // import interface configuration file import {request} from '.. /.. /utils/request' // Import Constants from '.. /.. /utils/Constants' // Import {Toast,Indicator} from 'mint-ui'; /utils/Constants' // Import {Toast,Indicator} from 'mint-ui'; Import md5 from 'js-md5'; Export default {data() {return {clean_time: ", // bind time clean_new_Time: ", // bind time to choose the time clean_Room: "", // bind the room number clean_new_Room: ", // bind the selected room number isShowClean_Room: false, // whether to display the room number mask authorization: HomeCodeList: [{flex: 1, values: ['8501', '8502', '8503', '8504', '8505', '8506', '8507', '8508'], className: 'homeCode', textAlign: 'center'}],}}, created(){/** * @simulation_login (); //that.simulation_login; this.simulation_login(); console.info('passing.... '); }, methods: {/** * @homecloseclick () {this.isshowclean_room = true; Console. log(" Select room number ")}, /** * @timecloSeclick click select time */ timeCloseClick() {this.clean_new_Time = new Date(); This.$refs.picker.open(); This. isShowHome_Time = true; Console. log(" Select time "); }, /** * @onValuesChange select option function * @param values selected option */ onValuesChange(values) {console.log(values.values[0]); this.clean_new_Room = values.values[0]; Clean_RoomCancel () {this.clean_new_room = this.clean_room; clean_RoomCancel() {this.clean_new_room = this.clean_room; this.isShowClean_Room = false; }, /** * @clean_roomConfirm click on the room number to confirm */ clean_RoomConfirm() {this.clean_room = this.clean_new_room; this.isShowClean_Room = false; }, /** * @select_time select time */ select_Time(){this.isshowhome_time = false; console.info(this.clean_new_Time); this.clean_time = this.clean_new_Time.format('yyyy-MM-dd HH:mm:ss'); // Format the time}, /** * @confirm_clean * @constants. Host_submit Submit interface */ confirm_clean(){if(this.clean_room && this.clean_time){ Request ({method: 'POST ', URL: Constants. Host_submit + api. clean_task_API, // Send a request to submit a cleaning data: {room_no: this.clean_Room, sweep_type : 0, sweep_time : this.clean_time, card_id : null, remark : '', }, /*headers : { authorization : this.authorization }*/ }).then((res)=>{ console.info(res); If (res.message === 'success'){Toast({message: 'success', iconClass: 'mint-toasts-icon mintui-success'}); }else{ let instance = Toast(res.message); setTimeout(() => { instance.close(); }, 2000); }}). The catch ((err) = > {let instance = Toast (' system exceptions); setTimeout(() => { instance.close(); }, 2000); console.error(err); }); }else{let instance = Toast(' please complete the information '); setTimeout(() => { instance.close(); }, 2000); }, /** * @simulation_login () {let username = 'hotel_root'; let pwd = '123456'; let code = 'SHJKJD-HND'; let shift_name = 'morning_shift'; request({ method : 'post', url : Constants.host_login + api.clean_employee_login, data : { code: code, user_name: username, password: md5(pwd), shift_name : shift_name } }).then((res)=>{ console.info(res); if(res.message === 'success'){ //this.authorization = res.new_authorization; sessionStorage.setItem('authorization',res.new_authorization); } else{console.error(' simulated login failed '); } }).catch((err)=>{ console.error(err); })}.}}Copy the code

Where you need to use it, you can import it directly. Of course, you can also reference it globally. All of these are ok.

That’s pretty much the end of it. Encapsulating a request isn’t hard, just familiarize yourself with the process. I am also in the help of others to achieve, just write more, thank you all the way to help me. Wish my friends and I a pleasant journey on the way to Vue.