Axios | Ajax | Await|Async | asy

2018-08-07  本文已影响0人  小淘气_嘻

Axios vs Ajax

Axios

安装

使用: axios(config) || axios(url[, config])

//创建请求
axios({
  method:' post ',
  url:   theurl,
  data: {
        firstName:'Fred',
        lastName:'Fline'
  }
})
//GET请求
axios
.get(url , {params:{ID:12345}})
.then(function(response){})
.catch(function(error){});
//POST请求
axios
.post(url,{firstName:'Fred',laseName:'Fline'})
.then(function(response){})
.catch(function(error){})\

特殊使用:执行多个并发请求

function getUserAccount(){
  return axios.get(url1);
}
function getUserPermissions(){
  return axios.get(url2);
}
axios
.all([  getUserAccount(), getUserPermission()  ])
.then(  axios.spread(function(acct,perms){
    //两个请求都执行完成
})  )

API

处理并发请求的函数

创建实例: axios.create([config])

配置项包括:

node.js标准库中有个querystring,这个库处理url查询字符串
qs 允许根据[]包围的查询字符串来创建嵌套对象
qs npm酷库:是querystring的增强版本,支持内嵌对象和数组

//querystring
const querystring = require('querystring');
querystring.parse('foo=bar&bar=1'); //即{ foo:‘bar’, baz:'1'}
querystring.parse('foo[bar] = 1&baz[]=2') ;//{ ‘foo[bar]’:1, 'baz[]': '2'}  意味着前端表单中存在数组,则标准库无法满足需求
//qs
const qs =  require('qs');
qs.parse('foo[bar] =1&bax[] =2'); //{foo:{ bar :'1'}, baz:['2']}

响应结构

//得到的响应信息
{
  data:{},   由服务器提供的响应
  status:200,  来自服务器响应的HTTP状态码
  statusText: 'OK',   来自服务器响应的HTTP状态信息 
  header:{},  服务器响应头
  config:{} 为请求提供的配置信息
}
//使用方法:
axios.get('/user/1234')
.then(function(response){
  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.header);
  console.log(response.config);
})

默认值/defaults

axios.defaults.baseURL = '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
//自定义实例默认值   并在实例已创建后修改默认值
var instance = axios.create({
  baseURL:'http://...'
})
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

拦截器

//请求和响应拦截器
axios.interceptors.request.use(function(config){ 
  //在发送请求之前
  return config;
},function(error){
  //应对请求错误
  return Promise.reject(error)
});
axios.interceptors.response.use(function(){  //在响应数据之前
},function(error){   // 应对响应错误
})
//移除拦截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
//为自定义的axios实例添加拦截器
var instance = axios.create();
instance.interceptors.request.use(...)

Await vs Async

Await

//串行:等待前一个await执行后再执行下一个await
async function asyncAwaitFn(str) {
   return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(str)
        }, 1000);
    })
}
const serialFn = async () => { //串行执行
    console.time('serialFn')
    console.log(await asyncAwaitFn('string 1'));
    console.log(await asyncAwaitFn('string 2'));
    console.timeEnd('serialFn')
}
serialFn();
//让多个await并行执行,再执行最后一个await
async function asyncAwaitFn(str) {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(str)
        }, 1000);
    })
}
const parallel = async () => { //并行执行
    console.time('parallel')
    const parallelOne = asyncAwaitFn('string 1');
    const parallelTwo = asyncAwaitFn('string 2')
    //直接打印
    console.log(await parallelOne)
    console.log(await parallelTwo)
    console.timeEnd('parallel')
}
parallel()

async/await错误处理

async function catchErr(){
  try{
     const erRes = await new Promise({resolve, reject} => {
          /*.....*/
      });
  }catch(err){  //处理错误情况 }
}

AsyncData

AsyncDara

export default{
  data(){      return{/*....**/}   },
  asyncData(context){     return {/*....*/}   }
}

Fetch

//fetch GET 请求,将参数写在url上 
//带参数的url :'https://www.baidu.com/search/error.html?a=1&b=2'
fetch( url, {  method:'GET'  })
.then(  (res)=>{ return res;   })
.then(  (res)=>{ return res;   })
//fetch POST请求 
//参数指定在fetch第二个参数中
//设置请求头 headers
//强制带cookie ,配置 credentials
fetch( url, {
  method:'POST',  //使用HTTP动词:GET, POST, PUT, DELETE, HEAD
  body: new URLSearchParams([['foo',1],['bar',2]]).toString(), //请求的对象数据
  headers: new Headers({      //关联的Header对象
      'Content-Type' :'application/x-www-form-urlencoded',    // 指定提交方式为表单提交
      ‘Accept’:'application/json' //指定获取数据的类型是JSON
  }),
  credentials:'include',    //是否发送Cookie,强制加入凭据头(omit, same-origin)
  mode: 'cors'   //请求的模式,设置跨域, 得到type:'opaque' 的返回,使用其进行信息上报(cors, no-cors, same-origin)
  integrity:'',  //完整性校验
  cache:'',  //缓存模式  (default, reload, no-cache)
  redirect:''  //收到重定向请求之后的操作 follow, error, manual
})
.then(  (res)=>{ 
      return res.json(); // 返回一个Promise, 可以解析成JSON  
})
.then(  (res)=>{
      console.log(res)  //获取到JSON 数据
})
//fetch封装
/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

/**
 * 真正的请求
 * @param url 请求地址
 * @param options 请求参数
 * @param method 请求方式
 */
function commonFetcdh(url, options, method = 'GET') {
  const searchStr = obj2String(options)
  let initObj = {}
  if (method === 'GET') { // 如果是GET请求,拼接url
    url += '?' + searchStr
    initObj = {
      method: method,
      credentials: 'include'
    }
  } else {
    initObj = {
      method: method,
      credentials: 'include',
      headers: new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      }),
      body: searchStr
    }
  }
  fetch(url, initObj).then((res) => {
    return res.json()
  }).then((res) => {
    return res
  })
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 请求参数
 */
function GET(url, options) {
  return commonFetcdh(url, options, 'GET')
}

/**
 * POST请求
 * @param url 请求地址
 * @param options 请求参数
 */
function POST(url, options) {
  return commonFetcdh(url, options, 'POST')
}

总结:Ajax | Axios | Fetch

Ajax

Axios

Fetch

fetch需要填的坑:

上一篇 下一篇

猜你喜欢

热点阅读