四:Vue前后端交互

一:概述

1接口调用方式

原生ajax
基于jQuery的ajax
fetch
axios

2:传统形式的URL

格式:schema://lost:port/path?query#fragment
1):schema:协议。例如http,https,ftp等
2);host:域名或者IP地址
3):port:端口,http默认端口80,可以省略
4):path:路径。例如/abc/a/b/b/c
5):query:查询参数,例如uname=lisi&age=12
6):fragment:瞄点(哈希Hash),用于定位某个位置。

3:URL地址格式—Restful形式的URL

HTTP请求方式
1):GET 查询
2):POST  添加
3):PUT 修改
4):DELETE 删除

符合规则的URL地址

1):http://www.hello.com/books GET
2):http://www.hello.com/books POST
3):http://www.hello.com/books/123 put
4):http://www.hello.com/books/123 DELETE

二:Promise用法

异步调用

异步效果分析

1:定时任务
2:AJAX
3:事件函数

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

1:多次异步调用的结果顺序不确定。
2:异步调用结果如果存在依赖需要嵌套。

Promise概述

Promise是异步编程的一种解决方案,从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。
使用Promise主要有以下好处:

可以避免多次嵌套问题(回调地狱)
Promise对象提供了简洁的API,使得控制异步操作更加容易

Promise概述

实例化Promise对象,构造函数中传递函数,该函数中用于处理异步任务。
resolve和reject两个参数用于处理成功和失败两种情况,并通过p.then获取处理结果。

var p =new Promise(function(resolve,reject){
	//成功时调用 resolve()
	//失败时调用 reject()
});
p.then(function(ret){
	//从resolve得到正常结果。
},function(ret){
	//从reject得到错误信息
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>前后端交互</div>
<script type="text/javascript">
    /*
        前后端交互-异步编程与Promise概述。
    */
    var p= new Promise(function (resolve,reject) {
        //这里用于实现异步任务。
        setTimeout(function () {
            var flag=true;
            if(flag){
                //正常情况
                resolve('hello');
            }else{
                //异常情况
                reject('出错了');
            }
        },100);
    });
    p.then(function (data) {
        console.log(data);
    },function (info) {
        console.log(info)
    })
</script>
</body>
</html>

基于Promise处理Ajax请求

1.处理原生Ajax

function queryData(){
	return new Promise(function(resolve,reject){
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange=function(){
			if xhr.readyState!=4) return ;
			if(xhr .status ==200){
				resolve(xhr.responseText)
				}else{
					reject('出错了’);
				}
			}
			xhr.open('get','/data');
			xhr.send(null);
			}}
			}

2:then参数中的函数返回值
1.返回Promise实例对象
返回的该实例对象会调用下一个then
2:返回普通值
返回的普通值直接传递给下一个then,通过then参数中的参数接收该值。

Promise常用的API

1:实例方法

p.then  得到异步任务的正确结果
p.catch()获取异常信息
p.finally()成功与否都会执行(尚且不是正式标准)
queryData()
.then(function(data){
	console.log(data);
})
.catch(function(data){
	console.log(data);
})
.finally(function(){
	console.log('finished');
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>前后端交互</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
    function foo() {
        return new Promise(function (resolve, reject) {
          setTimeout(function () {
              //resolve(123);
              reject('error');
          },100);
        });
    }
   /* foo()
        .then(function (data) {
            console.log(data);
        })
        .catch(function (data) {
            console.log(data);
        })
        .finally(function () {
            console.log('finished');
        });*/
    foo()
        .then(function (data) {
            console.log(data);
        },function (data) {
            console.log(data);
        })
        .finally(function () {
            console.log('finished');
        })
</script>
</body>
</html>

6:Promise常用的的API
对象方法

Promise.all()并发处理多个异步任务,所以任务都执行完成才能得到结果
Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果。
Promise.all([p1,p2,p3]).then((result =>{
	console.log(result)
})
Promise.race([p1,p2,p3]).then((result =>{
	console.log(result)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
    function queryData(url) {
        return new Promise(function(resolve, reject){
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState != 4) return;
                if(xhr.readyState == 4 && xhr.status == 200) {
                    // 处理正常的情况
                    resolve(xhr.responseText);
                }else{
                    // 处理异常情况
                    reject('服务器错误');
                }
            };
            xhr.open('get', url);
            xhr.send(null);
        });
    }
    var p1=queryData('http://localhost:3000/a1');
    var p2=queryData('http://localhost:3000/a2');
    var p3=queryData('http://localhost:3000/a3');
    Promise.all([p1,p2,p3]).then(function (result) {
        console.log(result);
        console.log('sss');
    });
</script>
</body>
</html>

接口调用-fetch用法

基本特性:
更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版。
基于Promise实现

语法结构
fetch(url).then(fn2)
			.then(fn3)
			...
			.catch(fn)
基本用法:
fetch('/abc').then(data=>{
	return data.text();
}).then(ret=>{
	//注意这里得到的才是最终的数据。
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API 基本用法
    */
    fetch('http://localhost:3000/fdata').then(function (data) {
        //text()方法属于fetchAPI的一部分,它返回一个Promise实例对象。用于获取后台获取的数据。
        return data.text();
    }).then(function (data) {
        console.log(data);
    })
</script>
</body>
</html>

fetch请求参数

1.fetch请求参数
method(String):HTTP请求方式,默认为GET(GET,POST,PUT,DELETE)
body(String):HTTP的请求参数
headers(Object):HTTP的请求头,默认为{}

```cpp
fetch('/abc',{
	method:'get'
}).then(data =>{
	return data.text();
}).then(ret=>{
	//注意这里得到的才是最终的数据.
	console.log(ret);
	});
GET请求方式的参数传递
fetch('/abc?id=123').then(data=>{
	return data.text();
}).then(ret=>{
	//注意这里得到的才是最终的数据。
	console.log(ret)
	})
或者
fetch('/abc/123').then(data=>{
	return data.text();
}).then(ret=>{
	//注意这里得到的才是最终的数据。
	console.log(ret)
	})
fetch('/abc?id=123',{
	method:'delete'
}).then(data=>{
	return data.text();
}).then(ret=>{
	//注意这里得到的才是最终的数据。
	console.log(ret)
	})

POST请求方式的参数传递

fetch('/books',{
	methods:'post',
	body:'uname=list&pwd=123',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded',
	}
}),then(data=>{
	return data.text();
}).then(ret=>{
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API 基本用法
    */
/*
   fetch('http://localhost:3000/books',{
        method:'post',
        body:'uname=lisi&pwd=123',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }).then(function (data) {
        //text()方法属于fetchAPI的一部分,它返回一个Promise实例对象。用于获取后台获取的数据。
        return data.text();
    }).then(function (data) {
        console.log(data);
    })
*/

    fetch('http://localhost:3000/books',{
        method: 'post',
        body: JSON.stringify({
            uname: '张三',
            pwd: '456'
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(function(data){
            return data.text();
        }).then(function(data){
        console.log(data)
    });
</script>
</body>
</html>

PUT请求方式的参数传递

fetch('/books',{
	methods:'put',
	body:JSON.stringify({
	uname:'lisi',
	age:12
	})
	headers:{
		'Content-Type':'application/json',
	}
}),then(data=>{
	return data.text();
}).then(ret=>{
	console.log(ret);
});

fetch响应结果

响应数据格式

text();将返回体处理成字符串类型
json:返回结果和JSON.parse(responseText)一样。
fetch('/abc' then(data=>{
	//return data.text();
	return data.json();
}).then(ret=>{
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API 基本用法
    */
    fetch('http://localhost:3000/json').then(function (data) {
        return data.json()
    }).then(function (data) {
        console.log(data);
    })
</script>
</body>
</html>

2:axios的基本用法

接口调用-axios用法

1.axios的基本特性
axios:是一个基于Promise用于浏览器和node.js的HTTP客户端。
它具有如下特性:

支持浏览器和node.js
支持promise
能拦截请求和响应
能自动转换JSON数据。
```cpp
axios.get('/data')
	.then(ret =>{
		//data属性名称固定的,用来获取后台响应的数据。
		console.log(ret.data)
		}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    axios.get('http://localhost:3000/adata').then(function (ret) {
        //z注意daa属性是固定的用法,用来获取后台的实际数据。
        console.log(ret);
    })
</script>
</body>
</html>

在这里插入图片描述

3:axios的常用API

get : 查询数据
post: 添加数据
put  : 修改数据
delete : 删除数据

axios的参数传递。
get传递参数

Get传递参数
	通过URL传递参数
	通过params选项传递参数。
方法一:
axios.get('/adata?id=123')
	.then(ret=>{
		console.log(ret.data)
})
方法二:
axios.get('/adata/123')
	.then(ret=>{
		console.log(ret.data)
})
方法3:
axios.get('/adata',{
	params:{
		id:123
	}
})
.then(ret=>{
	console.log(ret.data)
})

2.DELETE传递参数

axios.delete('/adata?id=123)
	.then(ret=>{
		console.log(ret.data)
})
axios.delete('/adata/123)
	.then(ret=>{
		console.log(ret.data)
})
axios.delete('/adata',{
	params:{
		id:123
	}
}).then(ret=>{
	console.log(ret.data)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">

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

</script>
</body>
</html>

3.axios的POST传递参数
通过选项传递参数:(默认传递的是json格式的数据)

axios.post('/adata',{
	uname:'tome',
	pwd:123
}).then(ret=>{
	console.log(ret.data)
})
通过URLSerchParams传递参数(application/x-www-form-urlencoded)
const params=new URLSerchParams();
params.append('patam1','value1');
params.append('param2','value2');
axios.post('/api/test',params).then(ret=>{
	console.log(ret.data)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    var params=new URLSearchParams();
    params.append('uname','zhangsan');
    params.append('pwd','123');
    axios.post('http://localhost:3000/axios',params).then(function (ret) {
        console.log(ret.data);
    })
</script>
</body>
</html>

4:PUT传递参数

axios.put('/adata/123',{
	uname:'tom,
	pwd:123
}).then(ret=>{
	console.log(ret.data)
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
  axios.put('http://localhost:3000/axios/123',{
      uname:'lisi',
      pwd:123
  }).then(function (ret) {
      console.log(ret.data)
  })
</script>
</body>
</html>

axios的响应结果

1:响应结果的主要属性

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

axios的全局配置

axios.defaults.timeout=3000;//超时时间
axios.defaults.baseURL='http:localhost:3000/app';//默认地址
axios.defaults.headers['mytoken'] = 'aqwerwqwerqer2wrwe23eresdf23'//设置请求头。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios的全局配置
    */
    //配置请求的默认的基准URL地址
    axios.defaults.baseURL='http://localhost:3000/';
    //配置请求头信息
    axios.defaults.headers['mytoken']='hello';
    axios.get('axios-json').then(function (ret) {
        console.log(ret);
    })

</script>
</body>
</html>

axios拦截器

1:请求拦截器
在请求发出之前设置一些信息。
在这里插入图片描述
代码实现

//添加一个请求拦截器
axios.interceptors.request.use(function(config){
	//在请求发出之前进行一些信息设置
	return config;
},function(err){
	//处理响应的错误信息
};
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios拦截器
    */
    axios.interceptors.request.use(function (config) {
        console.log(config.url);
        //拦截器配置请求头
        config.headers.mytoken='nihao';
        return config;
    },function (err) {
        console.log(err);
    });

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

</script>
</body>
</html>

2:响应拦截器
在获取数据之前对数据做一些加工处理。
在这里插入图片描述

//添加一个响应拦截器
axios.interceptors.response.use(function(res){
	//在这里对返回的数据进行加工处理
	return res;
},function(err){
//处理响应的错误信息
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios拦截器
    */
    axios.interceptors.request.use(function (config) {
        console.log(config.url);
        //拦截器配置请求头
        config.headers.mytoken='nihao';
        return config;
    },function (err) {
        console.log(err);
    });
    axios.interceptors.response.use(function (res) {
        console.log(res);;
        var data=res.data;
        return data;
    },function (err) {
        console.log(err);
    });
    axios.get('http://localhost:3000/adata').then(function (ret) {
        console.log(ret)
    });

</script>
</body>
</html>


接口调用async和await用法

async/await是ES7引入的新语法,可以更加方便的进行异步操作。
async关键字用于函数上(async函数的返回值是Promise实例对象)
await关键字用于async函数当中(await可以得到异步的结果)

async function queryData(id){
	Const ret=await axios.get('/data');
	return ret;
}
queryData.then(ret=>{
	console.log(ret)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
      async/await 处理异步操作:
      async函数返回一个Promise实例对象
      await后面可以直接跟一个 Promise实例对象
    */
    axios.defaults.baseURL = 'http:localhost:3000';
    // axios.get('adata').then(function(ret){
    //   console.log(ret.data)
    // })

 /*   async function queryData() {
        var ret = await axios.get('adata');
        console.log(ret.data)
        //return ret.data;
    }*/

     async function queryData() {
       var ret = await new Promise(function(resolve, reject){
         setTimeout(function(){
           resolve('nihao')
         },1000);
       })
       // console.log(ret.data)
       return ret;
     }
     queryData().then(function(data){
       console.log(data)
     })
</script>
</body>
</html>

接口调用async和await处理多个异步请求

多个请求的场景

async function queryData(id){
	const info await axios.get('/async1');
	const ret=await axios.get('async2?info='+info.data);
	return ret;
}
queryData.then(ret=>{
	console.log(ret)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        async/await处理多个异步任务
    */
    axios.defaults.baseURL='http://localhost:3000';
    async function queryData() {
        var info = await axios.get('async1');
        var ret = await axios.get('async2?info=' + info.data);
        return ret.data;
    }
    queryData().then(function(data){
        console.log(data)
    })
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值