How to simply encapsulate axios in vue

How to simply encapsulate axios in vue

Inject axios into Vue

import axios from 'axios';
Vue.prototype.$axios = axios;
import axios from 'axios'

axios.defaults.timeout = 5000; //Response time axios.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8'; //Configure request header axios.defaults.withCredentials= true; //With cookie
axios.defaults.baseURL = 'http://localhost:8080/'; //Configure interface address //POST parameter serialization (add request interceptor)
axios.interceptors.request.use((config) => {
	//You can add serialization code here, depending on the backend. The SSM backend I use accepts Json objects. If serialization is required, you can use the qs component return config;
},(error) =>{
    console.log('wrong parameter passing')
    return Promise.reject(error);
});

//Return status judgment (add response interceptor)
axios.interceptors.response.use((res) => {
    //Do something with the response data if (!res.data.success) {
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    console.log('network abnormality')
    return Promise.reject(error);
});

//Return a Promise (send a post request)
export function fetchPost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
Returns a Promise (sends a get request)
export function fetchGet(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: param})
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
export default {
    fetchPost,
    fetchGet,
}

Simple test:

loginPost: function() {
		let params = {
			'password': '123',
			'username': 'admin'
		}
		http.fetchPost('/login', params).then((data) => {
			console.log(data)
		}).catch(err => {
			console.log(err)
		})
	},
hello: function() {
		http.fetchGet('/hello', "").then((data) => {
			console.log(data)
		}).catch(err => {
			console.log(err)
		})
	},

Post request:

Get request:

Cross-domain problem, here is the configuration on the backend:

Configure cross domain in SpringMVC.xml:

<!-- Interface cross-domain configuration -->
    <mvc:cors>
        <!-- allowed-methods="*" --> <!-- means all requests are valid -->
        <mvc:mapping path="/**" allowed-origins="*"
                     allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                     allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
                     allow-credentials="true"/>
    </mvc:cors><!-- Interface cross-domain configuration-->

Interface configuration:

Configure in Vue Create a vue.config.js:

module.exports = {
  devServer: {
    proxy: {
        '/api': {
            target: 'http://127.0.0.1:8080',
            // A virtual server will be created locally, and then the requested data will be sent and received at the same time, so that there will be no cross-domain problem when the server and the server interact with each other. changeOrigin: true, 
            ws: true,
            pathRewrite: {
                '^/api': '' 
                // Replace the request address in target, that is to say, when you request the address http://api.jisuapi.com/XXXXX in the future, just write /api}
        }
    }
  }
}

The backend can also obtain cookies normally.

Of course, pay attention to the following configuration, this is the reason for the cookie

axios.defaults.withCredentials = true;

Summarize

This is the end of this article about how to simply encapsulate axios in vue. For more relevant vue encapsulation axios content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed example of using typescript to encapsulate axios in Vue3
  • How to encapsulate axios in Vue
  • How to encapsulate axios request with vue
  • Several ways to encapsulate axios in Vue
  • Detailed explanation of AXIOS encapsulation in Vue

<<:  How to insert a value containing single quotes or backslashes in MySQL statements

>>:  Tutorial on installing MYSQL8.X on Centos

Recommend

Detailed explanation of uniapp's global variable implementation

Preface This article summarizes some implementati...

CSS implements six adaptive two-column layout methods

HTML structure <body> <div class="w...

How to implement form validation in Vue

1. Installation and use First, install it in your...

mysql-8.0.17-winx64 deployment method

1. Download mysql-8.0.17-winx64 from the official...

Detailed explanation of MySQL date addition and subtraction functions

1. addtime() Add the specified number of seconds ...

Implementation steps of encapsulating components based on React

Table of contents Preface How does antd encapsula...

CSS3 custom scroll bar style::webkit-scrollbar sample code detailed explanation

The default scroll bar style in Windows is ugly, ...

Is it easy to encapsulate a pop-up component using Vue3?

Table of contents Summary put first: 🌲🌲 Preface: ...

Vue realizes click flip effect

Use vue to simply implement a click flip effect f...

Detailed analysis of mysql MDL metadata lock

Preface: When you execute a SQL statement in MySQ...

Simple setup of VMware ESXi6.7 (with pictures and text)

1. Introduction to VMware vSphere VMware vSphere ...

vue-cli configuration uses Vuex's full process record

Table of contents Preface Installation and Usage ...

How to use vue3 to build a material library

Table of contents Why do we need a material libra...

The difference and choice between datetime and timestamp in MySQL

Table of contents 1 Difference 1.1 Space Occupanc...

Vue+node realizes audio recording and playback function

Result: The main part is to implement the code lo...