Vue接口調(diào)用方式(一)fetch用法

?目錄總覽:

1. fetch概述

基本特性

  • fetch是傳統(tǒng)ajax的升級版本,是原生js
  • 更加簡單的數(shù)據(jù)獲取方式,功能更強(qiáng)大,更靈活,可以看作是xhr的升級版。
  • 基于Promise實(shí)現(xiàn)

語法結(jié)構(gòu)

fetch(url).thne(fn2)
         .thne(fn3)
         ...
         .then(fn)

2. fetch的基本用法

  • 第一個(gè).then接收到的是Promise數(shù)據(jù)集
  • 需要被.then處理才可以看到 我們最終想要的數(shù)據(jù)。
//客戶端請求
<body>
  <script type="text/javascript">
    //Fetch API 基本用法
    fetch('http://localhost:3000/fdata').then(function(data){
      // text()方法屬于fetchAPI的一部分,它返回一個(gè)Promise實(shí)例對象,用于獲取后臺(tái)返回的數(shù)據(jù)
      return data.text();
    }).then(function(data){
      console.log(data);
    })
  </script>
</body>

//服務(wù)器響應(yīng)
app.get('/fdata', (req, res) => {
  res.send('Hello Fetch!')
})

3. fetch請求參數(shù)

常用配置選項(xiàng):

  • method(String):HTTP請求方法,默認(rèn)為GET(GET、DELETE、POST、PUT)
  • body(String):HTTP請求參數(shù)
  • headers(Object):HTTP的請求頭,默認(rèn)為{}
3.1 get請求方式的參數(shù)傳遞
第一種方式
//客戶端請求
<body>
  <script type="text/javascript">
  //GET參數(shù)傳遞-傳統(tǒng)URL
    fetch('http://localhost:3000/books?id=123', {
      method: 'get'
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
  </script>
</body>

//服務(wù)器響應(yīng)
app.get('/books', (req, res) => {
  res.send('傳統(tǒng)的URL傳遞參數(shù)!' + req.query.id)
})
第二種方式(restful形式的url)
//客戶端請求
<body>
  <script type="text/javascript">
  //GET參數(shù)傳遞 - restful形式的URL
    fetch('http://localhost:3000/books/456', {
      method: 'get'
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服務(wù)器響應(yīng)
app.get('/books/:id', (req, res) => {
  res.send('Restful形式的URL傳遞參數(shù)!' + req.params.id)
})
3.2 delete請求方式的參數(shù)傳遞
//客戶端請求
<body>
  <script type="text/javascript">
    //DELETE請求方式參數(shù)傳遞
    fetch('http://localhost:3000/books/789', {
      method: 'delete'
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服務(wù)器響應(yīng)
app.delete('/books/:id', (req, res) => {
  res.send('DELETE請求傳遞參數(shù)!' + req.params.id)
})
3.3 post請求方式的參數(shù)傳遞
  • body用于向后臺(tái)傳遞數(shù)據(jù)
  • headers請求頭需要配置content-type內(nèi)容類型(后面的值是固定的),才可以傳過去
第一種方式

傳遞的是傳統(tǒng)格式的參數(shù)

//客戶端請求
<body>
  <script type="text/javascript">
    //POST請求傳參
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: 'uname=lisi&pwd=123',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服務(wù)器響應(yīng)
app.post('/books', (req, res) => {
  res.send('POST請求傳遞參數(shù)!' + req.body.uname + '---' + req.body.pwd)
})
第二種方式

傳遞的是Json格式的參數(shù)

//客戶端請求
<body>
  <script type="text/javascript">
    //POST請求傳參
    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>

//服務(wù)器響應(yīng)
app.post('/books', (req, res) => {
  res.send('POST請求傳遞參數(shù)!' + req.body.uname + '---' + req.body.pwd)
})
  • 可以接受json格式參數(shù)的原因:有bodypaser中間鍵
3.4 put請求方式的參數(shù)傳遞
  • put請求方式的參數(shù)傳遞:一般提交的數(shù)據(jù),用于修改原有數(shù)據(jù)
    • put也支持第一種 傳遞傳統(tǒng)表單text形式的參數(shù)
    • json格式需要后臺(tái)提供支撐,也就是bodyParser中間鍵
//客戶端請求
<body>
  <script type="text/javascript">
    //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)
      });
  </script>
</body>

//服務(wù)器響應(yīng)
app.put('/books/:id', (req, res) => {
  res.send('PUT請求傳遞參數(shù)!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

4. fetch響應(yīng)結(jié)果

  • text():將返回體處理成字符串類型
  • json():返回結(jié)果和JSON.parse(responseText)一樣
第一種方式text
//客戶端請求
<body>
  <script type="text/javascript">
    //Fetch響應(yīng)text數(shù)據(jù)格式
    fetch('http://localhost:3000/json').then(function(data){
      return data.text();
    }).then(function(data){
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })
  </script>
</body>

//服務(wù)器響應(yīng)
app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})
  • data類型為字符串,無法直接訪問屬性的值

處理方式(訪問到具體屬性值):

1.使用JSON.parse()把字符串轉(zhuǎn)化成對象
var obj = JSON.parse(data)
2.使用 obj.屬性名 得到屬性值
console.log(obj.uname)
第二種方式j(luò)son
//客戶端請求
<body>
  <script type="text/javascript">
    //Fetch響應(yīng)json數(shù)據(jù)格式
    fetch('http://localhost:3000/json').then(function(data){
      return data.json();
    }).then(function(data){
      console.log(data.uname)
    })
  </script>
</body>

//服務(wù)器響應(yīng)
app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})
  • 返回的data是object對象,可以直接獲取對象中屬性的值 (data.屬性名)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容