• fetch的使用方法(基于promise方法进行增删改查)


    js代码:

    class FetchHttp {
        // 封装get请求
        get(url){
            return new Promise((resolve, reject)=>{
                fetch(url)
                .then(data=>resolve(data.json()))
                .catch(err=>reject(err))
            })
        }
    
        // 封装post请求
        post(url, data){
        //也可以基于async 和await来实现如下promise代码
        // async post(url, data){
        //     const res = await fetch(url, {
        //         method:'post',
        //         headers: {'Content-type': 'application/json'},
        //         body: JSON.stringify(data)
        //     })
    
        //     return await res.json()
        // }
            return new Promise((resolve, reject)=>{
                fetch(url, {
                    method:'post',
                    headers: {'Content-type': 'application/json'},
                    body: JSON.stringify(data)
                })
                .then(data=>resolve(data.json()))
                .catch(err=>reject(err))
            })
        }
    
        // 封装put请求
        put(url, data){
            return new Promise((resolve, reject)=>{
                fetch(url, {
                    method:'put',
                    headers: {'Content-type': 'application/json'},
                    body: JSON.stringify(data)
                })
                .then(data=>resolve(data.json()))
                .catch(err=>reject(err))
            })
        }
    
    
        // 封装delete请求
        delete(url, data){
            return new Promise((resolve, reject)=>{
                fetch(url, {
                    method:'delete',
                    headers: {'Content-type': 'application/json'},
                })
                .then(data=>resolve('数据删除成功'))
                .catch(err=>reject(err))
            })
        }
    }

    前端实现代码:

      const http = new FetchHttp();  //调用构造函数
    
    
        // 查询数据的请求
        http.get('http://jsonplaceholder.typicode.com/users')
        .then(data=>{ console.log(data)})
        .catch(err=>{ console.log(err)})
    
    
        // 提交数据的请求
        http.post('http://jsonplaceholder.typicode.com/posts/', {name:'小红', age: 16, sex:''})
        .then(data=>{ console.log(data)})
        .catch(err=>{ console.log(err)})
    
    
        // 更新数据的请求
        http.put('http://jsonplaceholder.typicode.com/users/1', {name:'小明', sex:'', phone:188888888})
        .then(data=>{ console.log(data)})
        .catch(err=>{ console.log(err)})
    
    
        // 删除数据的请求
        http.delete('http://jsonplaceholder.typicode.com/users/3')
        .then(data=>{ console.log(data)})
        .catch(err=>{ console.log(err)})
  • 相关阅读:
    带锚点URL同一页面滚动效果的实现
    思路先行
    transliteration -- 2个功能
    html5 section article
    fields('t')
    使用Bootstrap
    JavaScript Switch
    菜单
    写一个博客页面
    自动适应
  • 原文地址:https://www.cnblogs.com/xuyx/p/11929437.html
Copyright © 2020-2023  润新知