current position:Home>Vue encapsulates multiple request requests (solution for multiple domain names)

Vue encapsulates multiple request requests (solution for multiple domain names)

2022-05-15 03:50:12wh20141212

The current project has two parts: foreground and background , The interface domain names used are also inconsistent , The requests that need to be intercepted are also inconsistent , Therefore, multiple... Are encapsulated request request , I have nothing to write today demo Well

  1. Can be in src Create a folder in the directory request Create under folder request.js file , You can encapsulate two request function , And then through export Expose

request.js file

//  introduce axios  Method 
import axios from "axios"
//  Introduce routing index file   The code jumps back to the landing page   Routing required  
import router from '../router/index'
//  introduce vuex  Warehouse   There was... In the previous code  dispatch Method   Those not used can be directly shielded 
//import store from '@/store'

 //  Foreground domain name interface encapsulation 
export function request1(config){
    
    //  establish axios example 
    const instance = axios.create({
    
        baseURL:"http://192.XXX.43.134:XXXX",  //  domain name 1
        timeout:5000
    })
    // request Interceptor 
    instance.interceptors.request.use(config => {
    
       // explain :  You can do some interception here 


        //  If it doesn't exist Code  Just intercept the interface 
        // console.log("config",config);
        //let code = JSON.parse(sessionStorage.getItem("origin"))
        //console.log(" Interception Office code",code);
        //if (code== null) {
    
            // HACK : At the intercept , If Code non-existent  todo........
            //store.dispatch('setOrigin')
       // }
        return config
    }, error => {
    
        console.error(' Interceptor error ',error) 
        Promise.reject(error)
    })
    // respone Interceptor 
    instance.interceptors.response.use(
        response => {
    
            // console.log(" Interceptor output ",response);
            return response
        },
        function (error) {
    
            console.log('err' , error)
            return Promise.reject(error)
        }
    )
  return instance(config)
}

//  Background interface domain name encapsulation 
export function requestLever(config){
    
    const instance = axios.create({
    
        baseURL:"http://192.XXX.133.213:XXXX",  //  domain name 2
        timeout:5000
    })
    //  Add a request interceptor 
    instance.interceptors.request.use(function (config) {
    
        // console.log(config)
        //  Judge whether it exists token, If there is to be every page header add to token
        // arr  The array is API White list   No validation required token The interface of   Requests can be made directly 
        let arr =[
            '/backstage/login/doLogin','/backstage/List'
        ]
        if( arr.includes( config.url )){
    
            return config
        }
        if (sessionStorage.getItem("token")) {
    
        	// There is token  Put it in the request header   Or jump to the landing page 
            config.headers.common['Authorization'] = sessionStorage.getItem("token");
        } else {
    
			// Not detected token  Return to the landing page 
            router.push('/login')
            return Promise.reject('error')
        }
        return config
    }, function (error) {
    
    	// If an error is reported, go back to the landing page 
        router.push('/login')
        return Promise.reject(error)
    })

  // respone Interceptor 
  instance.interceptors.response.use(
        response => {
    
            // console.log(" Interceptor output ",response);
            return response
        },
        function (error) {
    
            console.error('err' + error)
            return Promise.reject(error)
        }
    )
  return instance(config)
}

  1. The next step is how to use it In order to facilitate the management of the interface stay src Created in the root directory API Folder
    Create... Under different domain names API file The front desk API file =》 reception.js as well as backstage API file =》backstage.js

reception.js file

import {
     request1 } from "../API/request";
// get Interface writing  ----  Interface 1
export function queryAllTree(params) {
    
    return request1({
    
        url: '/api/queryAllTree',
        method: 'get',
        params: params
    })
}
// post  Interface writing ----  Interface 2
export function childernTree(params) {
    
    return request1({
    
        url: '/api/childernTree',
        method: 'post',
        data: params
    })
}

backstage.js file

import {
     requestLever} from "../API/request";

// The template list  get  request 
export function formTemplateList(params){
    
    return requestLever({
    
        url: '/form/list',
        method: 'get',
        params: params
    })
}

//  Update the form  post  request 
export function formTemplateUpdate(params){
    
    return requestLever({
    
        url: '/form/update',
        method: 'post',
        data: params
    })
}
  1. How to use it Introduce the corresponding interface in the page Then ask

Any page that needs to be requested

<template>
  <div class="tools_open">
		 Interface usage page 
  </div>
</template>

<script>
// Where is the interface written API In file   Just import... From the corresponding file 
import {
     queryAllTree } from '@/API/reception'
export default {
    
  data() {
    
    return {
    }
  },
  computed:{
    },
  mounted(){
    
      this.getInit()
  },
  methods: {
    
    getInit() {
    
    	  // Enter the reference 
          let params = {
    
            "pageIndex": 0,
            "pageSize": 8,
            "pubDate": "",
          }
          queryAllTree (params).then(res => {
    
            console.log(" Data query ", res.data)
            return
            //  Judge according to your own return parameters 
            if (res.data.statusCode == 200) {
    
              // console.log(res.data.data)
            } else {
    
              console.log('error:' ,res.data.message)
            }
          }).catch((err) => {
    
            console.log(err);
          })
    }
  }
}
</script>

<style scoped lang= "less"></style>

All right. Here is the complete packaging process It is hereby recorded that You can also use it directly in the future

 Insert picture description here

copyright notice
author[wh20141212],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/131/202205111510511815.html

Random recommended