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:12【wh20141212】
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
- 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)
}
- 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
})
}
- 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
copyright notice
author[wh20141212],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/131/202205111510511815.html
The sidebar is recommended
- Build an electron project based on Vue from scratch
- In Vue project, solve the problem of verification conflict when eslint and prettier are used at the same time
- Vue3 + vuecli4 solve chunk vendors JS file is too large. Scheme summary
- Scheme summary of eslint check before vue3 + vite configuration project operation and eslint check before git submission
- Fatal authentication failed for 'httpxxxx Git 'solution
- Vue's solution to the compatibility of hevc encoded video in each end browser
- Record the solution to the error in obtaining the picture in springboot in Vue
- [Vue] detailed analysis of the life cycle function of Vue components
- [Vue] deeper understanding of user-defined attribute props
- [Vue] front end error: cannot read properties of undefined (reading 'split')
guess what you like
[Vue] asynchronous problem of component value transfer -- the sub component gets the data slowly
[Vue] Vue data changes, but the page is not updated in real time
[element UI] use of form verification -- detailed explanation
[Vue] use of slots - Review
The influence on the fixed positioning element of the inner layer when the outer element has a fixed height and overflows and rolls
Precautions
Change detection strategy of angular component
Angular service and @ injectable
JS, HTML and CSS are not compatible and do not use common knowledge
Properties to be known in angular @ component
Random recommended
- Angular acquisition and operation DOM
- Html2canvas problem
- Use day in Vue JS (time and date processing library)
- Vue cli configuring preprocessor global variables (take less as an example)
- How to use H5 custom tags in Vue?
- Come on, vue2 customize global loading
- Come on, Vue move the end suspension ball assembly
- React routing foundation and transmission parameters
- Come on, Vue graphic verification code component
- JavaScript judges browser types and kernels at home and abroad (including 360, QQ, Sogou, etc.)
- ArcGIS JavaScript 4. Generates a rectangular buffer at the point of X
- Node under window JS installation, environment configuration, setting Taobao image
- Understanding of prototype and prototype object of JavaScript
- How to customize the startup port of react project!
- Why vue3 0 using proxy to realize data listening 2021-06-21
- Front end artifact - download, configuration and use process of Charles (vase) [Mac version]
- React next configures SVG loader and supports SVG configurability
- React native Android phone cannot be opened after installation. Flash back!
- Fetch and Axios failed to request on Android, with error messages: network request failed and network error
- How to upgrade react Babel 7.1.0
- babel7. 0 compatible with IE browser
- Nginx configuring reactrouter browserhistory browserrouter
- JS, react use html2canvas page screenshot and export
- Big data front-end visualization screen -- the road of front-end development
- [a quick introduction and comparison of multiple languages -- JavaScript, typescript, python, golang, trust, Java, ruby]
- Vue element admin login function, token filling, language conversion, routing setting
- Summation of corresponding position elements of multiple lists in Python
- Discussion on HTML page knowledge
- Using Ajax to realize non refresh paging
- HTTP format
- Zhang San has a meal - did he eat the difference between get and post in HTTP?
- The ultimate actual combat of the most complete tourism project based on spring boot + Vue front-end and back-end separation in history (with source code attached), none of them!!!
- Vue basic grammar
- LeetCode 217. There are duplicate elements
- Pagoda does not configure the solution of SSL site accessing HTTPS and jumping to other websites
- Vue3 isProxy
- About the problem that the container will hang up after starting nginx in the docker container
- Introduction to JavaScript
- The core element of large-scale software design is to control complexity. What is the root cause?
- What are the core elements of large-scale software design?