ES7 async封装fetch库(增删改查)

    科技2022-08-24  105

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> // 使用Promise封装fetch库(增删改查) 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, data){ const response = fetch(url, { method:"DELETE", headers:{ 'Content-type': 'application/json' } }) const resData = await "数据删除成功" return resData } } const http = new EasyHttp; // get请求数据 http.get('http://jsonplaceholder.typicode.com/users') .then((data) => { console.log(data) }) .catch(err => console.log(err)) //post const data = { name:"xiangming", username:"小明", email:"1231231@qq.com" } http.post('http://jsonplaceholder.typicode.com/users',data) .then((data) => console.log(data)) .catch(err => console.log(err)) //put http.put('http://jsonplaceholder.typicode.com/users/2',data) .then((data) => console.log(data)) .catch(err => console.log(err)) //delete http.delete('http://jsonplaceholder.typicode.com/users/2') .then((data) => console.log(data)) .catch(err => console.log(err)) </script> </head> <body> </body> </html>
    Processed: 0.008, SQL: 9