Vue前后端路由

前后端交互

1.接口调用方式

  • 原生ajax
  • 基于jquery的ajax
  • fetch
  • axios

url地址

  • 传统形式的url——schema://host:port/path?query#fragment

    • scheme:协议,如http,https,ftp
    • host:域名或IP地址
    • port:端口
    • path:路径
    • query:查询参数,如uname=lisi&age=12
    • fragment:锚点(hash),用于定位页面的某个位置
  • Restful形式的url——http请求方式

    • GET 查询
    • POST 添加
    • PUT 修改
    • DELETE 删除

2.异步调用

  • 异步效果分析

    • 定时任务,setTimeout,setInterval
    • ajax
var ret ='---'
$.ajax{
    // 后台接口express写的
    url:'http://localhost:3000/data',
    success:function(data){
        ret = data;
        console.log(ret); //data值
    }
}
console.log(ret) //--- ajax异步调用
  • 事件函数

  • 多次异步调用的依赖分析

    • 多次异步调用的结果顺序不确定,与写的顺序无关
    • 异步调用结果如果存在依赖需要嵌套===》回调地狱

3.promise

异步编程的一种解决方案,是一个对象。

好处:

可以避免多层异步调用嵌套问题(回调函数)

Promise对象提供了简洁的API,使控制异步操作更加容易

①基本用法

  • 实例化Promise对象,构造函数中传递函数,该函数体内实现异步任务

  • resolve和reject两个参数用于处理成功和失败两种情况,并通过p.then获取处理结果

var p = new Promise(function(resolve, reject){
    // 这里用于实现异步任务
    setTimeout(function(){
        var flag = true;
        if(flag){
            // 正常情况
            resolve('hello');
        }else{
            // 异常情况
            reject('出错了');
        }
    },100);
});

p.then(function(data){
    // 从resolve得到正常结果
},funtion(info){
       // 从reject得到错误信息
})

②基于Promise处理Ajax请求

function queryData(url){
    var p = new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        
        xhr.onreadystatechange=function(){
            if(xhr.readyState!=4) return;
            else(xhr.readyState ==4 && xhr.status == 200){
                // 处理正常情况
                resolve(xhr.responseText);
            }else{
                // 处理异常情况
                reject('服务器错误');
            }
        };
        
        // 准备发送前参数 (发送方式,url地址,异步)
        xhr.open('get',url);
        
        xhr.send(null);
    });
    return p;
}

queryData('http://localhost:3000/data')
    .then(function(data){
        // 从resolve得到正常结果
    },funtion(info){
        // 从reject得到错误信息                                         
    });

发送多次ajax请求并且保证顺序

queryData('http://localhost:3000/data')
    .then(function(data){
        // 从resolve得到正常结果
    	return queryData('http://localhost:3000/data1');
    })
    .then(function(data){
    	// 从resolve得到正常结果
    	return queryData('http://localhost:3000/data2');
    })
    .then(function(data){
    	// 从resolve得到正常结果
	  });

then参数中的函数返回值

  • 返回新的Promise实例对象

    返回的该实例对象会调用下一个then

  • 返回普通值

    返回的普通值会直接传递给下一个then,通过then参数中函数的参数接收该值

    (产生一个默认promise对象,从而保证下一个then可以链式操作)

③实例方法

  • p.then(参数1) 得到异步任务的正确结果
  • p.catch()获取异常信息
  • p.finally() 成功与否都会执行

p.then(参数1,参数2) 异步任务的结果(正确和异常结果)

④对象方法

Promise.all() 并发处理多个异步任务,所有任务都执行完成才能得到结果

var p1 = queryData('http://localhost:3000/data1');
var p2 = queryData('http://localhost:3000/data2');
var p3 = queryData('http://localhost:3000/data3');
Promise.all([p1,p2,p3]).then(function(result){
    // 返回的result是数组,顺序和传入的对象一一对应
});

Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果

4.fetch

基于promise实现,更加简单

①基本使用

text()属于fetch API的一部分,返回一个Pormise实例对象,用于获取后台返回的数据

fetch('http://localhost:3000/data2').then(function(data){
    return data.text();
}).then(function(data){
    // 真实的数据
})

②请求参数

method(String):http的请求方法,默认为get(get,post,put,delete)

body(String):http的请求参数

headers(Object):http的请求头,默认为{}

1️⃣get请求传递参数,delete类似

  • 传统
fetch('http://localhost:3030/books?id=123',{
  method:'get'
}).then(function(data){
  return data.text()
}).then(function(data){
    console.log(data)
})

// 后台
app.get('/books',(req,res)=>{
    res.send('传统的URL传递参数'+req.query.id)
})
  • restful
fetch('http://localhost:3030/books/456',{
    method:'get'
}).then(function(data){
    return data.text()
}).then(function(data){
    console.log(data)
})

// 后台
app.get('/books/:id',(req,res)=>{
    res.send('Restful形式的URL传递参数'+req.params.id)
})

2️⃣post请求

fetch('http://localhost:3030/books',{
    method:'post',
    body:'uname=lisi&pwd=123',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded'
    }
}).then(function(data){
    return data.text()
}).then(function(data){
    console.log(data)
})

// 后台
app.post('/books',(req,res)=>{
    res.send('Post请求传递参数'+req.body.uname+'------'+req.body.pwd)
})

JSON形式的参数

fetch('http://localhost:3030/books',{
    method:'post',
    body:JSON.stringify({
        uanme:'张三',
        pwd:'123'
    }),
    headers:{
        'Content-Type':'application/json'
    }
}).then(function(data){
    return data.text()
}).then(function(data){
    console.log(data)
})

3️⃣put请求 修改参数

fetch('http://localhost:3030/books/123',{
    method:'put',
    body:JSON.stringify({
        uanme:'张三',
        pwd:'456'
    }),
    headers:{
        'Content-Type':'application/json'
    }
}).then(function(data){
    return data.text()
}).then(function(data){
    console.log(data)
})

// 后台
app.put('/books/:id',(req,res)=>{
    res.send('Put请求传递参数'+req.params.id+'------'+req.body.uname+'------'+req.body.pwd)
})

③响应结果

text() 将返回体处理成字符串类型

json() 返回结果和JSON.parse(responseText)一样

fetch('http://localhost:3000/json',{
}).then(function(data){
    return data.json()
}).then(function(data){
    console.log(data)
})

// 后台
app.get('/json',(res,req)=>{
    res.json({
        uname:'lisi',
        age:12,
        gender:'male'
    })
})

5.axios

基于Promise用于浏览器和node.js的HTTP客户端

特性:

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 自动转换JSON数据

①基本使用

data属性是固定的用法,用于获取后台的实际数据

axios.get('http://localhost:3000/data').then(function(ret){
    console.log(ret.data)
})

②常用API

1️⃣get,delete类似

  • 通过url传递参数:url?id=123

    • 传统
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
    console.log(ret.data)
})

// 后台
app.get('/axios',(req,res)=>{
    res.send('axios get传递参数'+req.query.id)
})
  • Restful
axios.get('http://localhost:3000/123').then(function(ret){
    console.log(ret.data)
})

// 后台
app.get('/axios/:id',(req,res)=>{
    res.send('axios get(Restful)传递参数'+req.params.id)
})
  • 通过params选项传递参数:
axios.get('http://localhost:3000/axios',{
    params:{
        id:789
    }
}).then(function(ret){
    console.log(ret.data)
})
// 后台
app.get('/axios',(req,res)=>{
    res.send('axios get传递参数'+req.query.id)
})

2️⃣post,put类似

  • 通过选项传递参数(默认传递json格式的数据)
axios.post('http://localhost:3000/axios',{
    uname:'lisi',    
    pwd:'789'
}).then(function(ret){
    console.log(ret.data)
})
// 后台
app.post('/axios',(req,res)=>{
    res.send('axios post传递参数'+req.body.uname+'---'+req.body.pwd)
})
  • 通过URLSearchParams传递参数(表单形式application/x-www-form-urlencoded)
var params = new URLSearchParams();
params.append('uname','zhangsan');
params.append('pwd','111');

axios.post('http://localhost:3000/axios',params).then(function(ret){
    console.log(ret.data)
}) 

③响应结果

  • 响应结果的主要属性

    • data:实际响应回来的数据
    • headers:响应头信息
    • status:响应状态码
    • statusText:响应状态信息
  • 全局配置

axios.defaults.timeout=3000; // 超时时间
axios.defaults.baseURL='http://localhost:3000/'; // 默认地址
axios.defaults.headers['mytoken']='aqwererrw123dad'; // 设置请求头,跨域需要后台支持。

④拦截器

  • 请求拦截器

    image-20200831214259319
axios.interceptors.request.use(function(config){
    // 请求发出前进行信息设置
    config.headers.mytoken = 'nihao';
    return config;
},function(err){
    // 处理响应的错误信息
    console.log(err);
})
  • 响应拦截器

    image-20200831214631856
axios.interceptors.response.use(function(res){
    // 获取数据之前对数据进行加工处理
    console.log(res)
    var data = res.data;
    return data;
},function(err){
    // 处理响应的错误信息
    console.log(err);
})

6.async/await

①基本用法

  • async/await是ES8引入的新语法,方便异步操作
  • async用于函数上,async函数的返回值是Promise实例对象
  • await用于async函数中,await可以得到异步的结果
async function queryData(id){
    const ret = await axios.get('/data');
    return ret.data;
}
queryData.then(data=>console.log(data))

②多个异步请求

async function queryData(id){
    const info = await axios.get('/async1');
    const ret = await axios.get('/async2?info='+info.data);
    return ret.data;
}
queryData.then(data=>console.log(data))
posted @ 2020-08-31 22:18  wattmelon  阅读(585)  评论(0编辑  收藏  举报