# Axios快速开始

# Axios的安装

npm i axios

# 执行 GET 请求

//方法一
axios.get('/user?ID=12345')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

//方法二
// 上面的请求也可以这样做
axios.get('/user', {
    params: {
        ID: 12345
    }
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

# 执行 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

# 执行多个并发请求

function getUserAccount() {
    return axios.get('/user/12345');
}

function getUserPermissions() {
    return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
    .then(axios.spread(function (acct, perms) {
        // 两个请求现在都执行完成
    }));

# API

// 发送 POST 请求
axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
});

// 发送 GET 请求(默认的方法)
axios('/user/12345');

# 创建实例

可以使用自定义配置新建一个 axios 实例

# axios.create([config])

const instance = axios.create({
    baseURL: 'https://some-domain.com/api/',//根路径地址
    timeout: 1000, //超时时间
    headers: {'X-Custom-Header': 'foobar'} //请求头
});

# 拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

//导入axios
import axios from 'axios'
import URL from '../API/URL'
//使用axios下面的create([config])方法创建axios实例,其中config参数为axios最基本的配置信息。
const API = axios.create({
    baseURL: URL.URL, //请求后端数据的基本地址,自定义
    timeout: 2000,                  //请求超时设置,单位ms
    //请求头
    headers: {
        'Content-Type': 'application/json'
    }
})


//配置请求拦截器
API.interceptors.request.use(config => {
    config.headers = config.headers || {}
    if (config.method = 'post') {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    return config
})


//配置响应拦截器
API.interceptors.response.use(res => {
    if (res.status !== 200) {
        return window.$showmsgs('请求失败')
    }
    console.log(res.data)
    return res.data
})

//导出我们建立的axios实例模块,ES6 export用法
export default API
上次更新: 3/31/2023, 3:36:19 PM