Axios
小于 1 分钟
Axios
- 2022/7/12
 
介绍💞
- 2019
 
Vue3插件玩法🍒
- npm install --save axios vue-axios
 - http://www.axios-js.com/zh-cn/docs/vue-axios.html
 - 使用
 
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
// axios 配置
axios.defaults.baseURL = "http://localhost:8000/"
axios.defaults.headers.common['Authorization'] = "YourAuthorization";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    return Promise.reject(error);
});
Vue.use(VueAxios, axios)
- Vue组件
 
this.axios.get("/banner/list").then((response) => {
    console.log(response.data)
})
this.axios.post("/banner/list").then((response) => {
    console.log(response.data)
})
Npm基本用法💔
- 介绍: Vue项目请使用上面配置,否则使用Npm用法
 - http://www.axios-js.com/zh-cn/
 - npm install axios
 
Http配置🌟
- Http.js
 
import axios from 'axios';
//请求超时5秒
axios.defaults.timeout = 5000;
//如果你要用到session验证码功能,让请求携带cookie,可以加上以下一行
axios.defaults.withCredentials = true
axios.defaults.baseURL ='http://192.168.43.80:8081/'; //请求base url
export function get(url, params={}, headers={}){
    return new Promise((resolve, reject) => {
        axios.get(url,{
            params: params,
            headers: headers
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}
export function post(url, params={}, headers={}){
    return new Promise((resolve, reject) => {
        axios.post(url,{},{
            params:params,
            headers:headers
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}
Api配置🍎
- api.js
 
//建议使用  //params为json对象,底层会自动解析参数-优先使用
import {get,post} from '../utils/http.js'
export const getUserList =   (params) => {
    return get('user/list',
        params
    )
};
- 使用
 
getUserList().then((res)=>{
        console.log(res)
        this.tableData = res.data.records;
})
