vue fetch 接口調用&參數傳遞


fetch概述

基本特性

  • 更加簡單的數據獲取方式,功能更強大、更靈活,可以看做是xnr的升級版
  • 基於Promise實現

語法結構

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

fetch的基本用法

fetch('/abc').then(function(data){
  //text()屬於feych的API的一部分,返回的是一個Promise實例對象,用於獲取后台返回的數據
  return data.text);
}.then(data => {
  console.log(data);
}))

fetch請求參數

常用配置選項

  • method(String):HTTP請求方法,默認為GET(GET、POST、PUT、DELETE)
  • body(String):HTTP的請求參數
  • headers(Object):HTTP的請求頭,默認{}
fetch('/abc',{
  methods: 'GET'
})
.then(data => {
  return data.text);
}.then(ret => {
  //注意這里得到的才是最終的數據
  console.log(ret);
}));

GET請求方式傳遞參數

fetch('/abc/123',{
  methods: 'GET'
})
.then(data => {
  return data.text);
}.then(ret => {
  //注意這里得到的才是最終的數據
  console.log(ret);
}));

后台獲取數據

app.get('/abc/:id',(req,res) => {
  res.send('Restful形式的URL傳遞參數!' + req.params.id);
})

DELETE請求方式傳遞參數

fetch('/abc/123',{
  methods: 'DELETE'
})
.then(data => {
  return data.text);
}.then(ret => {
  //注意這里得到的才是最終的數據
  console.log(ret);
}));

DELETE后台獲取數據

app.delete('/abc/:id',(req,res) => {
  res.send('delete形式的URL傳遞參數!' + req.params.id);
})

POST請求方式傳遞參數

fetch('/abc',{
  methods: 'POST',
  //用於傳遞實際參數
  body : 'uname=list&pwd=123',
  //進行配置 必須設置
  headers:{
    'Content-Type' : 'application/x-www-form-urlencode'
  } }) .then(data
=> {   return data.text); }.then(ret => {   console.log(ret); }));

后台獲取數據

app.post('/abc',(req,res) => {
  res.send('Restful形式的URL傳遞參數!' + req.bbody.uname + '---' + req.body.pwd);
})

POST請求方法的JSON參數傳遞

fetch('/abc',{
  methods: 'POST',
  body : JSON.stringify({
    uname : 'list',
    pwd : 123
  }),
  headers:{     'Content-Type' : 'application/json'   } }) .then(data => {   return data.text); }.then(ret => {   console.log(ret); }));

PUT請求方式傳遞參數

fetch('/abc/123',{
  methods: 'put',
  body : JSON.stringify({
    uname : 'list',
    pwd : 123
  }),
  headers:{     'Content-Type' : 'application/json'   }}) .then(data => {
  
return data.text);
}.then(ret
=> {
  console.log(ret);
  })
);

后台獲取數據

app.get('/abc/:id',(req,res) => {
  res.send('put形式的URL傳遞參數!' + req.params.id + req.bbody.uname + '---' + req.body.pwd); 
})

fetch響應結果

響應數據格式

  • text():將返回體處理成字符串類型
  • json():返回結果和JSON.parse(reponseText)一樣
fetch('/abc')
.then(data => {
  return data.text);
}.then(ret => {
  //注意這里得到的才是最終的數據
  console.log(ret);
}));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM