Vue全家桶-前后端交互

一、前后端交互模式

1.接口调用方式:

原生ajax,

基于jQuery的Ajax

fetch

axios

2.URL地址格式

①传统形式的url

格式:

Schema://host:port/path?query#fragent

Schema-协议,http,https,ftp等

host-域名或ip地址

port-端口,http默认端口是80,可以省略

path-路径

query-查询参数,例uname=li

frament-锚点,hash,用于定位页面的某个位置

②Restful形式的URL

HTTP请求方式

GET 查询

POST 添加

PUT  修改

DELETE  删除

符合规则的url地址

http://www.hello.com/books  GET

http://www.hello.com/books  POST

http://www.hello.com/BOOKS/123  PUT

http://www.hello.com/BOOKS/123  DELETE

二、Promise用法

1.异步调用

异步效果分析:

定时任务

Ajax

事件函数

多次异步调用的依赖分析,多次异步调用的结果顺序不确定,异步调用结果如果存在依赖需要嵌套

2.Promise概述

Promise是异步编程的一种解决方案,从语法上讲promise是一个对象,从它可以获取异步操作的消息,好处:可以避免多层异步调用嵌套问题

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

三、接口调用-fetch用法

1.fetch概述

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

基于Promise实现。

语法:

fetch(url).then(fn2)

          .then(fn3)

          .then(fn)

          ....

          .catch(fn)

2.fetch基本用法

fetch('/abc').then(data => {

      return data.text();//text()属于fetch API的一部分,返回值是一个Promise实例对象,用于获取后台返回的数据

      }).then(ret => {

      //注意这里是得到的最终的数据

          console.log(ret)

})

示例

fetch('http://localhost:3000/fdata').then(function (data){

      return data.text();

}).then(function(data){

    console.log(data);

})

3.fetch请求参数

①常用配置选项

method(String):http请求默认方法,默认为GET(GET,POST,PUT,DELETE)

body(String):http的请求参数

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

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',{

    method: 'get'

}).then(data => {

    return data.text();

}).then(ret => {

  //注意这里得到的才是最终的数据

    console.log(ret);

});

③DELETE请求方式传递参数

fetch('/abc/123',{

    method: 'delete'

}).then(data => {

    return data.text();

}).then(ret => {

  //注意这里得到的才是最终的数据

    console.log(ret);

});

④POST请求方式的传递参数

fetch('/books',{

    method: 'post',

    body:'uname=lisi&pwd=123',

    headers: {

      'Content-Type': 'application/x-www-form-urllencoded',

}

}).then(data => {

    return data.text();

}).then(ret => {

    console.log(ret);

});

⑤PUT请求方式传递参数

fetch('/books/123',{

    method: 'put',

    body: JSON.stringify({

      uname:'lisi',

      age:12

    })

    headers: {

      'Content-Type': 'applicatio/json',

}

}).then(data => {

    return data.text();

}).then(ret => {

    console.log(ret);

});

4.fetch响应结果

响应数据格式

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

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

fetch('/abc').then(data =>{

    return data.json();

}).then(ret =>{

    console.log(ret);

});

四、接口调用-axios用法

axios是用于调用后台接口的js库

1.axios的基本特性

axios是一个基于Promise用于浏览器和node.js的http客户端。官网https://github.com/axis/axios

具有以下特性

支持浏览器和node.js

支持promise

能拦截请求和响应

自动转换JSON数据

2.axios的基本用法

先引入axios.js

axios.get('/adata')

    .then(ret => {

    //data属性名称是固定的,用于获取后台响应的数据

    console.log(ret.data);

})

3.axios常用API

get  查询数据

post  添加数据

put  修改数据

delete  删除数据

4.axios的参数传递

① GET传递参数

通过url传递参数

通过params选项传递参数

app.get('/axios',(req,res) =>{

    res.send('axios get 传递参数'+req.query.id)

})

axios.get('/axios?id=123')

      .then(ret=>{

          console.log(ret.data)

      })

app.get('/axios/:id',(req,res) =>{

    res.send('axios get (Restful) 传递参数'+req.params.id)

})

axios.get('/axios/123')

      .then(ret=>{

          console.log(ret.data)

      })

通过params选项传递参数-比较方便

app.get('/axios',(req,res) =>{

    res.send('axios get 传递参数'+req.query.id)

})

axios.get('/axios',{

    params : {

      id :123

    }

  })

    .then(ret=>{

    console.log(ret.data)

})

②DELETE传递参数-与GET传参类似

app.delete('/axios',(req,res) =>{

    res.send('axios delete 传递参数'+req.query.id)

})

axios.delete('/axios?id=123')

      .then(ret=>{

          console.log(ret.data)

      })

app.delete('/axios/:id',(req,res) =>{

    res.send('axios delete(Restful)传递参数'+req.params.id)

})

axios.delete('/axios/123')

      .then(ret=>{

          console.log(ret.data)

      })

通过params选项传递参数-比较方便

app.delete('/axios',(req,res) =>{

    res.send('axios delete 传递参数'+req.query.id)

})

axios.delete('/axios',{

    params : {

      id :123

    }

  })

    .then(ret=>{

    console.log(ret.data)

})

③POST传递参数

通过选项传递参数(默认传递的是json格式的数据)

app.post('/axios',(req,res)=>{

  res.send('axios post 传递参数'+ req.body.name)

})

axios.post('/axios',{

    uname:'tom',

    pwd:123

}).then(ret => {

    console.log(ret.data)

})

通过URLSearchParams传递参数(application/x-www-form-urllencoded)

const params = new URLSearchParams();

params.append('uname', 'zhngsan');

params.append('pwd', '123');

axios.post('/axios',params).then(ret =>{

    console.log(ret.data)

})

④PUT传递参数

参数传递方式与POST类似

app.put('/axios:id',(req,res)=>{

  res.send('axios put 传递参数'+ req.params.id+req.body.name)

})

axios.put('/axios/123',{

    uname:'tom',

    pwd:123

}).then(ret => {

    console.log(ret.data)

})

通过URLSearchParams传递参数(application/x-www-form-urllencoded)

const params = new URLSearchParams();

params.append('uname', 'zhngsan');

params.append('pwd', '123');

axios.put('/axios',params).then(ret =>{

    console.log(ret.data)

})

5.axios的响应结果

响应结果的主要属性

data:实际响应回来的数据

headers:响应头信息

status:响应状态码

statusText:响应状态信息

axios.post('/axios-json').then(ret=>{

console.log(ret)

})

6.axios的全局配置

axios.defaults.timeout = 3000; //超时时间

axios.defaults.baseURL = 'http://localhost:3000/app'; //默认地址,配置信息基准地址

axios.defaults.headers[ 'mytoken' ] = aqwerwqwerqwer2ewrwe23eresdf23' //设置请求头

7.axios拦截器

①请求拦截器

在请求发出之前设置一些信息

axios  请求拦截器    --->服务器

添加一个请求拦截器

axios.interceptors.request.use(function(config){

    config.headers.mytoken='nihao';

  //在请求发出之前进行一些信息设置

  return config;

},function(err) {

  //处理响应的错误信息

});

axios.get('http://localhost:3000/adata').then(function(data){

  console.log(data);

})

②响应拦截器

在获取数据之前对数据做一些加工处理

axios 响应拦截器 <----服务器

添加一个响应拦截器

axios.interceptors.response.use(function(res){

  //在这里对返回的数据进行处理

  var data = res.data;

  return data;

},function(err) {

  //处理响应的错误信息

});

axios.get('http://localhost:3000/adata').then(function(data){

  console.log(data);

})

五、接口调用-async/await用法

1.async/await基本用法

async/await是ES7引入的新语法,可以更加方便的进行异步操作

async关键字用于函数上(async函数的返回值是Promise实例对象)

await关键字用于await函数中(await可以得到异步的结果)

async function queryData(id) {

    const ret = await axios.get('/data/');

    return ret;

}

queryData.then(ret=>{

    console.log(ret);

})

2.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)

})

你可能感兴趣的:(Vue全家桶-前后端交互)