Skip to content

Files

Latest commit

author
cpzhang
Jun 20, 2018
ec6f65c · Jun 20, 2018

History

History
115 lines (105 loc) · 3.58 KB

4-axios.md

File metadata and controls

115 lines (105 loc) · 3.58 KB

发送请求

  1. 原生的xhr(XMLHttpRequest)
var xhr = new XMLHttpRequest();
xhr.open('GET','www.test.com',true);  //open(method,url,async)
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); setRequestHeader(header,value)
xhr.withCredentials=true; // 跨域携带cookie时需设置
xhr.send();

xhr.onreadystatechange = function(){
    if(xhr.readyState===4 && xhr.status===200){
        console.log(xhr.responseText);
        console.log(xhr.responseXML);
    }
}
  1. jquery 或 zepto 的ajax (对原生XHR进行了封装)
$.ajax({
    type:'POST',
    url:url,
    contentType: 'application/json',
    dataType: 'text/xml',
    data:data,
    success:function(){},
    beforeSend:function(req){
        req.setRequestHeader('header','value');
        req.withCredentials=true;  // 跨域携带cookie时需设置
    }
    error:function(){}
})
  1. fetch (ES6,基于promise设计)
fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  return response.text()
}, function(error) {
  error.message //=> String
})

当接收到一个代表错误的 HTTP 状态码时,从 fetch()返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ), 仅当网络故障时或请求被阻止时,才会标记为 reject。 默认情况下, fetch 不会从服务端发送或接收任何 cookies, 如果站点依赖于用户 session,则会导致未经认证的请求(要发送 cookies,必须设置 credentials 选项).

  1. axios (对原生xhr的封装,支持promise,提供了并发请求的接口)
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  withCredentials: true  // 跨域携带cookie时需设置
}).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) {
    // Both requests are now complete
  }));
  
// 请求或相应拦截
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (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);
  });
$ npm install --save axios

兼容性

参考

  1. 从ajax到fetch、axios
  2. Jquery ajax, Axios, Fetch区别之我见
  3. axios全攻略