Vue前端交互模式

 

前后端交互模式

接口调用方式

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

Promise用法

异步调用

异步效果分析

  • 定时任务
  • Ajax
  • 事件函数

多次异步调用的依赖分析

  • 多次异步调用的结果顺序不确定
  • 异步调用结果如果存在依赖需要嵌套(回调地狱)
var p = new Promise(function(resolve,reject){
	//成功调用resolve()
	//失败调用reject()
});
p.then(function(ret){
	//从resolve得到正常结果
},function(ret){
	//从reject得到错误信息
})
处理原生Ajax
function queryData(url) {
        return p = 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);
    });
    }
    
    queryData('http://localhost:3000/data')
        .then((data)=>{
            console.log(data);
        },(error)=>{
            console.log(error);
        })
发送多次ajax请求
queryData('http://localhost:3000/data')
        .then((data)=>{
            console.log(data);
            return queryData('http://localhost:3000/data1')
        })
        .then((data)=>{
            console.log(data);
            return queryData('http://localhost:3000/data2')
        })
        .then((data)=>{
            console.log(data); 
        })

then参数中的函数返回值

  • 返回Promise实例对象
    • 返回的该实例对象会调用下一个then
  • 返回普通值
    • 返回的普通值会传递给下一个then
Promise常用api
  • 实例方法
    • .then
    • .catch
    • .finally
Promise.then((data)=>{
            console.log(data);
        },(data)=>{
            console.log(data);
        })
        .finally(()=>{
            console.log('finished');
        })
  • 对象方法
    • .all 并发处理多个异步任务,所有任务都执行完成才能得到结果
    • .race 并发处理多个异步任务,只要有一个任务都执行完成才能得到结果
  • fetch
    
      //基本用法
      fetch('http:localhost:3000/fdata')
          .then((data)=>{
              //text()方法属于fetch API的一部分,他返回一个Promise实例对象
              return data.text();
          })
          .then((data)=>{
          	//这里的data才是
              console.log(data);
          })
      //常用配置选项
    	1.method(String):HTTP请求方法,默认为GET(GET,POST,DELETE)  
    		1.1 get请求方式的参数传递
    		//API
    		app.get('/books/:id',(req,res)=>{
      		res.send('Result!'+req.params.id)
          })
          //方法
    		fetch('http:localhost:3000/books/111',{
              	method:'get'
          	})
          	.then((data)=>{
              	//text()方法属于fetch API的一部分,他返回一个Promise实例对象
              	return data.text();
          	})
          	.then((data)=>{
              	console.log(data);
          	})
          1.2 delete请求方式的参数传递
          //API
    		app.get('/books/:id',(req,res)=>{
      		res.send('Result!'+req.params.id)
          })
          //方法
          fetch('http:localhost:3000/books/789',{
              method:'delete'
          })
          .then((data)=>{
              //text()方法属于fetch API的一部分,他返回一个Promise实例对象
              return data.text();
          })
          .then((data)=>{
              console.log(data);
          })
          1.3 post请求方式的参数传递
          //API
          app.post('/books',(req,res)=>{
      		res.send('post请求的URL传递参数!'+req.body.uname + req.body.pwd)
          })
          //方法1
          fetch('http:localhost:3000/books',{
              method:'post',
              body:'uname=zhangsan&pwd=123',
              headers:{
                  'Content-Type':'application/x-www-form-urlencoded'
              }
          })
          .then((data)=>{
              //text()方法属于fetch API的一部分,他返回一个Promise实例对象
              return data.text();
          })
          .then((data)=>{
              console.log(data);
          })
          //方法2(JSON形式)
          fetch('http:localhost:3000/books',{
              method:'post',
              body:JSON.stringify({
                  uname:'张三',
                  pwd:'123456'
              }),
              headers:{
                  'Content-Type':'application/json'
              }
          })
          .then((data)=>{
              //text()方法属于fetch API的一部分,他返回一个Promise实例对象
              return data.text();
          })
          .then((data)=>{
              console.log(data);
          })
            
           1.4 put请求方式的参数传递
          //API
          app.post('/books/:id',(req,res)=>{
      		res.send('put请求的URL传递参数!'+req.params.id + req.body.uname + 						req.body.pwd)
          })
          fetch('http:localhost:3000/books/123',{
              method:'put',
              body:JSON.stringify({
                  uname:'张三',
                  pwd:'123456'
              }),
              headers:{
                  'Content-Type':'application/json'
              }
          })
          .then((data)=>{
              //text()方法属于fetch API的一部分,他返回一个Promise实例对象
              return data.text();
          })
          .then((data)=>{
              console.log(data);
          })
       2.body(String):HTTP的请求参数
       3.headers(Object):HTTP的请求头,默认为{}
    
  • axios

    //API
    app.get('/adata',(req,res)=>{
        res.send('Hello Axios')
    })
    //方法
    axios.get('http:localhost:3000/adata')
            .then(res=>{
            	//data属性名称是固定的,用于获取后台响应的数据
                console.log(res.data)
            })
    
    • get(查询数据)

      //方式一
      //API
      app.get('/axios',(req,res)=>{
          res.send('Axios get 传递参数'+req.query.id)
      })
      //方法
      axios.get('http:localhost:3000/axios?id=123')
              .then(res=>{
                  console.log(res.data)
              })
      //方式二
      //API
      app.get('/axios/:id',(req,res)=>{
          res.send('Axios get 传递参数'+req.params.id)
      })
      //方法
      axios.get('http:localhost:3000/axios/123')
              .then(res=>{
                  console.log(res.data)
              })
      //方式三
      //API
      app.get('/axios/:id',(req,res)=>{
          res.send('Axios get 传递参数'+req.params.id)
      })
      //方法
      axios.get('http:localhost:3000/axios',{
      	params:{
      		id:999
      	}
      })
              .then(res=>{
                  console.log(res.data)
              })
      
    • post(添加数据)

      //方式一(JSON类型)
      //API
      app.post('/axios',(req,res)=>{
          res.send('Axios post 传递参数'+req.body.uname+req.body.pwd)
      })
      //方法
      axios.post('http:localhost:3000/axios',{
                  uname:'zhangsan',
                  pwd:123
              })
              .then(res=>{
                  console.log(res.data)
              })
                  
      //方式二(字符串类型)
      //API
      app.post('/axios',(req,res)=>{
          res.send('Axios post 传递参数'+req.body.uname+req.body.pwd)
      })
      //方法
      var params = new URLSearchParams();
              params.append('uname','张三')
              params.append('pwd','123456')
              axios.post('http:localhost:3000/axios',params)
              .then(res=>{
                  console.log(res.data)
              })
      
    • put(修改数据)

      //API
      app.put('/axios/:id',(req,res)=>{
          res.send('Axios post 传递参数'+req.params.id+req.body.uname+req.body.pwd)
      })
      //方法
      axios.put('http:localhost:3000/axios/123',{
                  uname:'zhangsan',
                  pwd:123
              })
              .then(res=>{
                  console.log(res.data)
              })
      
    • delete(删除数据)

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