21.

Http

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script src="easyhttp.js"></script>
  <script src="app.js"></script>
</body>
</html>

app.js

const http = new EasyHttp;

// 請求數(shù)據(jù)
// http.get("http://jsonplaceholder.typicode.com/users")
//     .then((data) => {
//       console.log(data);
//     })
//     .catch(err => console.log(err))

// 傳輸數(shù)據(jù)
const data = {
  name:"Henry",
  username:"米斯特吳",
  email:"27732357@qq.com"
};

// post user
// http.post("http://jsonplaceholder.typicode.com/users",data)
//     .then(data => console.log(data))
//     .catch(err => console.log(err));

// update user
// http.put("http://jsonplaceholder.typicode.com/users/2",data)
//     .then(data => console.log(data))
//     .catch(err => console.log(err));

// delete user
http.delete('http://jsonplaceholder.typicode.com/users/2')
    .then(data => console.log(data))
    .catch(err => console.log(err));

esayhttp

/**
 * 封裝fetch
 * 更快,更簡單的請求數(shù)據(jù)
 *
 * @version 2.0.0
 * @author  米斯特吳
 * @license MIT
 *
 **/

 class EasyHttp{
   // get 
   async get(url){
     const response = await fetch(url);
     const resData = await response.json();
     return resData;
   }

   // post
   async post(url,data){
      const response = await fetch(url,{
         method:"POST",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       });
      const resData = await response.json();
      return resData;
  }

  // put
  async put(url,data){
      const response = await fetch(url,{
         method:"PUT",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       });

       const resData = await response.json();
       return resData;    
  }

  // delete
  async delete(url){
      const response = await fetch(url,{
        method:"DELETE",
        headers:{
          'Content-type':'application/json'
        }
      })
      const resData = await "數(shù)據(jù)刪除成功!";
      return resData;
  }
 }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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