JavaScript之axios

Axios 作弊表(Cheat Sheet)
GET 请求
//get请求, 字符串请求
axios.get('/user?ID=1234').then((response)=>{
    console.log(response);
}).catch((error)=>{
    console.log(error);
})
//get请求,param请求
axios.get('/user',{
    params:{
        ID:12345
    }
}).then((response)=>{
    console.log(response);
}).catch((error)=>{
    console.log(error);
})
axios({
    method:'get',
    url: 'http://bit.ly/2323',
    responseType:'stream'
}).then((response)=>{
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
POST 请求
axios.post('/user',{
    fisrtName:'xiaobang',
    lastName:'sky'
}).then((response)=>{
    console.log(response);
}).catch((error)=>{
    console.log(error);
})

axios({
    method:'POST',
    url:'/user/12345',
    data:{
        firstName: 'Fred',
        lastName:'hahah'
    }
})
并行请求
getUserAccount = ()=>{
    return axios.get('/user/12345');
}
getUserPermissions = ()=>{
    return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()]).then((acct,permissions)=>{
    console.log(acct);
    console.log(permissions);
}).catch((error)=>{
    console.log(error);
});
创建实例
const axiosObj = axios.create({
    baseURL:'https://some-domain.com/api/',
    timeout:1000,
    headers:{'X-Custom-Header':'foot'}
});
Response
axios.get('/user/12345').then((response)=>{
    let data = response.data,
        status =response.status,
        statusText = response.statusText,
        headers = response.headers,
        config = response.config;
})
Config
//axios defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//Custom instance defaults
// Set config defaults when creating the instance
let instance = axios.create({
    baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Config order of precedence
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
    timeout: 5000
});
拦截器
// Intercept request/responses
// Add a request interceptor
axios.interceptors.request.use(config=>{
    // Do something before request is sent
    return config;
},error=>{
    // Do something with request error
    return Promise.reject(error);
})
// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});
// Remove interceptor
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
// Custom instance interceptors
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
  
错误处理
// Catch error

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

// Custom HTTP status code error

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})
取消请求
// Cancel request with cancel token

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

// Create cancel token

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值