axios

290 阅读2分钟

juejin.cn/post/684490…

juejin.cn/post/684490…

juejin.cn/post/684490…

juejin.cn/post/684490…

juejin.cn/post/684490…

juejin.cn/post/684490…

juejin.cn/post/684490…

案例:www.jianshu.com/p/c9e05ac3a…

axios内部运作流程 image.png

原生ajax

  • 优点:局部更新;原生支持
  • 缺点:可能破坏浏览器后退功能;嵌套回调 原生ajax及4个步骤和过程:
var xhr = new XMLHttpRequest();//1、创建异步对象 
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//2、设置请求基本信息,并加上请求头
    xhr.open('post', 'test.php' ,'true');//3、配置用get还说post请求,发送的url请求是否是异步
    xhr.send('name=Lan&age=18');//4、发送请求
    xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {// 这步为判断服务器是否正确响应
       console.log(xhr.responseText);} };//获取异步调用返回的数据

手写ajax:

  function ajx(url) {
        const p = new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest() //初始化一个实例
            xhr.open('GET', url, true) //true是开启异步请求,false是同步请求
            chr.onreadystatechange = function () {
                if (xhr.readystate === 4) {
                    //0未初始化,还未调用send()、1载入,已调send(),正在发送请求,2载入完成,send()执行完成,已接受全部响应内容,3交互:正在解析响应内容还未发送回来,4完成:响应内容解析完成,可在客户端调用
                    if (xhr.status === 200) {
                        //状态码,2XX:成功处理请求,3xx需要重定向,浏览器直接跳转,4xx客户端请求错误,5xx服务端错误
                        resolve(JSON.parse(xhr.responseText))
                    } else if (xhr.status === 404) { reject(new Error('404 not found')) } }} 
xhr.send(null)
})
        return p }
    const url = '/data/test.json'
    ajx(url).then(res => console.log(res)).catch(err => console.log(err))

jqueryAjax

在原生的ajax的基础上进行了封装;支持jsonp

var loginBtn =  document.getElementsByTagName("button")[0];
loginBtn.onclick = function(){
    ajax({
        type:"post",
        url:"test.php",
        data:"name=lan&pwd=123456",
        success:function(data){
           console.log(data);
        }
    });
}

fetch

  • 优点:解决回调地狱
  • 缺点:API 偏底层,需要封装;默认不带Cookie,需要手动添加; 浏览器支持情况不是很友好,需要第三方的ployfill
fetch('http://www.mozotech.cn/bangbang/index/user/login', {
    method: 'post',
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams([
        ["username", "Lan"],["password", "123456"]
    ]).toString()
})
.then(res => {
    console.log(res);
    return res.text();
})
.then(data => {
    console.log(data);
})

axios

  • 特点:
    • 支持浏览器和node.js
    • 支持promise
    • 能拦截请求和响应
    • 能转换请求和响应数据
    • 能取消请求
    • 自动转换JSON数据
    • 浏览器端支持防止CSRF(跨站请求伪造)
axios({
    method: 'post',
    url: '/abc/login',
    data: {
        userName: 'Lan',
        password: '123'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

同时发起多个请求:

image.png 如何将axios异步请求同步化处理?

//使用 asyns/await 
async getHistoryData (data) {
 try {
   let res = await axios.get('/api/survey/list/', {
     params: data
   })
   this.tableData = res.data.result
   this.totalData = res.data.count
 } catch (err) {
   console.log(err)
   alert('请求出错!')
 }
}

如何中断(取消)axios的请求?

image.png axios怎么解决跨域的问题?几种跨域方式了解一下

借鉴阅读