Axios parameter configuration (commonly used)

usage

axios({
    
    
  method: 'get', // post、get、put、delete....
  baseURL: '', // 请求的域名,基本地址,公共的路径
  url: '', // 请求的路径
  params: {
    
    }, // get参数会将请求参数拼接在url上
  data: {
    
    }, // post会将请求参数放在请求体中
  headers: {
    
    }, // 设置请求头,例如设置token等
  timeout: 1000, // 设置请求超时时长,单位:ms
  withCredentials:default,//表明了是否是跨域请求、默认是default
  maxContentLength:1000//相应内容的最大值
})

Note on other writing methods: Parameters with [] indicate that they are not required parameters, and without [] indicates that they are required parameters.

axios.request(config)
axios.get(url, [config])
axios.post(url, [data], [config]])
axios#delete(url[, config])

Configure defaults

1、全局配置baseURL[URL三个字母必须大写,不然axios不认]
axios.defaults.baseURL = '公共路径';
如:axios.defaults.baseURL = 'https://baidu.com';
axios.defaults.timeout = 1000;
在实际项目中,很少用全局配置。
2、实例配置
const instance = axios.create({
    
    
  baseURL: 'http://localhost:8888/api/private/v1/',
  timeout: 1000,
})
//方法一
instance.get('/getUserInfo').then(res => {
    
    
  // ...
})
//方法二
axios.defaults.baseURL = 'http://localhost:8888/api/private/v1/';
getright() {
    
    
            return axios.get("rights/list").then(res=>{
    
    })
        },
3、请求配置
//方法一
const instance = axios.create();
instance.get('/getUserInfo', {
    
    
  timeout: 5000
})
//方法二
  install(Vue) {
    
    
 // 将axios添加到vue.prototype上
Vue.prototype.$getright = getright;
    }
-----------------------------------
注:配置的优先顺序
全局 < 实例 < 请求

Concurrent processing [one page requests multiple interfaces]

同时进行多个请求,并统一处理返回值
axios.all(iterable)
axios.spread(callback)
例:
axios.all([
  axios.post('/addusers',{
    
    name:'yannn',age:22}),
  axios.detete('/delete',{
    
    id:2})
]).then(axios.spread((add, del) => {
    
    
  console.log(add, del);
}))

Summarize

The above is a summary of the more commonly used parameter configurations and the use of axios requests. I hope it is useful to you~~~~

Guess you like

Origin blog.csdn.net/Yannnnnm/article/details/112195610