Promise、Fetch、Axios入門以及學習總結,涉及Express搭建接口

基於Promise發送原生Ajax請求javascript

// 基於Promise發送原生Ajax請求
    function queryData(url) {
      //resolve請求成功的回調函數  reject請求失敗的回調函數
      var 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);
      });
      return p;
    }

    // 發送多個ajax請求而且保證順序
    queryData('http://localhost:3000/data')
      .then(function(data){
        console.log(data)
        return queryData('http://localhost:3000/data1');
      })
      //這裏的then指向的是上面return的promise對象
      .then(function(data){
        console.log(data);
         return 'hello';
      })
       //這裏的then指向的是上面return返回新建立的promise對象
      .then(function(data){
        console.log(data)
      });

異步任務API
.then(function(data){})  任務成功執行的函數
.catch(function(error){})    任務出錯執行的函數
.finally(function(){})  不管成功出錯都會執行的函數
.race([a,b,..])  參數是一個數組,數組是promise對象,該方法是執行數組內全部的異步函數,返回最快執行完的一個promise對象結果
.all([a,b,..]) 參數是一個數組,數組是promise對象,該方法須要全部的異步函數執行完纔會返回結果
 java

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)
    })
    Promise.race([p1,p2,p3]).then(function(result){
      console.log(result)
    })

Fetch(用法跟promise相似)

Fetch API是新的ajax解決方案 
Fetch會返回Promise fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象node

//使用Express框架搭建服務器
const express = require('express')
const app = express()
// Express框架默認使用body-parser做爲請求體解析中間件
const bodyParser = require('body-parser')
// 處理靜態資源
app.use(express.static('public'))
// 處理參數
app.use(bodyParser.json());
// false表示使用系統模塊querystring來處理,也是官方推薦的,true即便用第三方模塊
app.use(bodyParser.urlencoded({ extended: false }));

// 設置容許跨域訪問該服務
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
  next();
});

//服務器端get請求接口一
app.get('/fdata', (req, res) => {
  res.send('Hello Fetch!')
})
 /*
    //客戶端請求代碼
    fetch('http://localhost:3000/fdata').then(function(data){
    // text()方法屬於fetchAPI的一部分,它返回一個Promise實例對象,用於獲取後臺返回的數據
      return data.text();
    }).then(function(data){
      console.log(data);
    })   
*/


//服務器端get請求接口二
app.get('/books', (req, res) => {
  // query是url的查詢參數
  res.send('傳統的URL傳遞參數!' + req.query.id)
})

/*
    //客戶端請求代碼
    //GET參數傳遞-傳統URL
    fetch('http://localhost:3000/books?id=123', {
      method: 'get'
    })
      .then(function(data){
        //將返回值轉換成字符串
        return data.text();
      }).then(function(data){
        // 輸出123
        console.log(data)
      });
*/


//服務器端get請求接口三
app.get('/books/:id', (req, res) => {
  // params是參數名
  res.send('Restful形式的URL傳遞參數!' + req.params.id)
})

/*
    //客戶端請求代碼
    //GET參數傳遞-restful形式的URL
    fetch('http://localhost:3000/books/456', {
      method: 'get'
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服務器端delete請求接口
app.delete('/books/:id', (req, res) => {
  res.send('DELETE請求傳遞參數!' + req.params.id)
})

/*
    //客戶端請求代碼
    //DELETE請求方式參數傳遞
    fetch('http://localhost:3000/books/789', {
      method: 'delete'
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服務器端post請求接口一
app.post('/books', (req, res) => {
  //這裏的body是通過解析中間件處理獲得的
  res.send('POST請求傳遞參數!' + req.body.uname + '---' + req.body.pwd)
})


/*
    //客戶端請求代碼
    //POST請求傳參
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: 'uname=lisi&pwd=123',
      headers: {
        //這裏必定要設置類型   類型爲:'uname=lisi&pwd=123'格式
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服務器端post請求接口二
app.put('/books/:id', (req, res) => {
  res.send('PUT請求傳遞參數!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

/*
    //客戶端請求代碼
    //POST請求傳參
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: JSON.stringify({
        uname: '張三',
        pwd: '456'
      }),
      headers: {
        //這裏設置的參數類型是json格式
        'Content-Type': 'application/json'
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服務器端put請求接口
app.put('/books/:id', (req, res) => {
  res.send('PUT請求傳遞參數!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

/*
    //客戶端請求代碼
    // PUT請求傳參
    fetch('http://localhost:3000/books/123', {
      method: 'put',
      body: JSON.stringify({
        uname: '張三',
        pwd: '789'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/

Axios

基於promise用於瀏覽器和node.js的http客戶端
支持瀏覽器和node.js 
支持promise 
能攔截請求和響應 
自動轉換JSON數據 
能轉換請求和響應數據 ios

axios基礎用法 
get和 delete請求傳遞參數 
經過傳統的url 以 ? 的形式傳遞參數 
restful 形式傳遞參數 
經過params 形式傳遞參數
 post 和 put 請求傳遞參數 
經過選項傳遞參數 
經過 URLSearchParams 傳遞參數ajax

//服務器端get接口一
// query查詢參數
app.get('/axios', (req, res) => {
  res.send(req.query.id)
})

/*
    //客戶端get請求傳參方式一
    axios.get('http://localhost:3000/axios?id=123').then(function(ret){
      console.log(ret.data)
    })
*/


//服務器端get接口二    params參數
app.get('/axios/:id', (req, res) => {
  res.send(req.params.id)
})

/*
    //客戶端get請求方式二
    axios.get('http://localhost:3000/axios/123').then(function(ret){
      console.log(ret.data)
    })
*/

/*
    //客戶端get請求方式三
    axios.get('http://localhost:3000/axios', {
      params: {
        id: 789
      }
    }).then(function(ret){
      console.log(ret.data)
    })
*/


//服務器端delete接口
app.delete('/axios', (req, res) => {
  res.send(req.query.id)
})

/*
    客戶端delete請求方式
    axios delete 請求傳參
    axios.delete('http://localhost:3000/axios', {
      params: {
        id: 111
      }
    }).then(function(ret){
      console.log(ret.data)
    })
*/


//服務器端post接口
app.post('/axios', (req, res) => {
  res.send(req.body.uname + '---' + req.body.pwd)
})

/*
    //客戶端post請求方式一 json格式
    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

    //客戶端post請求方式二 字符串格式   經過URLSearchParams 傳遞參數
    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)
    })
*/


//服務器端put接口
app.put('/axios/:id', (req, res) => {
  res.send(req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

/*
    //客戶端post請求方
    axios.put('http://localhost:3000/axios/123', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })
*/

axios 全局配置 express

// 配置請求的基準URL地址
    axios.defaults.baseURL = 'http://localhost:3000/';
    // 配置 超時時間 
    axios.defaults.timeout = 2500;
    // 配置請求頭信息
    axios.defaults.headers['mytoken'] = 'hello';
    //由於配置的基準url地址,此處url不用重複寫
    axios.get('axios-json').then(function(ret){
      console.log(ret.data.uname)
    })

axios 攔截器 
一、請求攔截器 
請求攔截器的做用是在請求發送前進行一些操做 
例如在每一個請求體里加上token,統一作了處理若是之後要改也很是容易 
二、響應攔截器 
響應攔截器的做用是在接收到響應後進行一些操做 
例如在服務器返回登陸狀態失效,須要從新登陸的時候,跳轉到登陸頁json

// 請求攔截器 
    axios.interceptors.request.use(function(config) {
      // 任何請求都會通過這一步   在發送請求以前作些什麼 
      //設置請求頭信息
      config.headers.mytoken = 'nihao';
      // 這裏必定要return   不然配置不成功 
      return config;
    }, function(err){});

    // 響應攔截器 
    axios.interceptors.response.use(function(res) {
      //在此處能夠對響應的內容作處理,以下將返回res的data內容。
      var data = res.data;
      return data;
    }, function(err){});

async 和 await 

async做爲一個關鍵字放到函數前面 
任何一個 async 函數都會隱式返回一個 promise 
await 關鍵字只能在使用 async 定義的函數中使用 
await後面能夠直接跟一個 Promise實例對象 
await函數不能單獨使用 
async/await 讓異步代碼看起來、表現起來更像同步代axios

//服務器端接口
app.get('/async1', (req, res) => {
  res.send('hello')
})
app.get('/async2', (req, res) => {
  if(req.query.info == 'hello') {
    res.send('world')
  }else{
    res.send('error')
  }
})

// 客戶端請求方式
    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)
    })
相關文章
相關標籤/搜索