fetch的增删查改

264 阅读1分钟

get请求

  • fetch默认就是get请求
  • get请求携带参数,url+?key=value&key=value
  • 语法:
// 异步
// url为请求地址
// 不带参数
async function get1(url) {
    let res = await fetch(url)
        .then(response => response.json())
        .catch(err => err.json())
    console.log(res);
} 
// 带参数:查询 q所有字段,模糊查询
async function get2(url) {
    let res = await fetch(url + "?q=新疆")
        .then(r => r.json())
        .catch(err => err.json())
    console.log(res);
}

post请求

  • 在请求体body中,传递参数
  • 需要修改数据格式为 key=value&key=value&
  • 还需要设置header的传输格式
  • 语法:
// 转换数据格式
const Params = (obj) => {
    let str = ""
    for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            str += `${key}=${obj[key]}&`
        }
    }
    return str
}
async function post(url) {
    // 要添加的数据
    let user = {
        name: "张三",
        age: 26,
        sex: "男",
        address: "江苏"
    }
    let res = await fetch(url, {
        method: "post",
        body: Params(user),
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        }
    }).then(response => response.json())
    console.log(res);
}

delete 请求

  • 删除
  • 语法:
async function del(url) {
    // 通过id删除
    let res = await fetch(url + "/" + 13, {
        method: "delete"
    }).then(r => r.json())
    console.log(res);
}

put 全部修改

  • PUT全部修改,相当于覆盖
  • 在请求体body中,传递参数
  • 需要修改数据格式为 key=value&key=value&
  • 还需要设置header的传输格式
  • 语法:
// 转换数据格式
const Params = (obj) => {
    let str = ""
    for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            str += `${key}=${obj[key]}&`
        }
    }
    return str
}
//put请求
async function put(url) {
    let user = {
        name: "李四",
        address: "北京"
    }
    // 修改id为14的人员信息
    let res = await fetch(url + "/" + 14, {
        method: "PUT",
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        },
        body: Params(user)
    }).then(r => r.json())
    console.log(res);
}

patch 部分修改

  • 在请求体body中,传递参数
  • 需要修改数据格式为 key=value&key=value&
  • 还需要设置header的传输格式
  • 语法:
// 转换数据格式
const Params = (obj) => {
    let str = ""
    for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            str += `${key}=${obj[key]}&`
        }
    }
    return str
}
async function patch(url){
    let user = {
        name: "喻言",
        age: 50
    }
    let res = await fetch(url + "/" + 15, {
        method: "PATCH",
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        },
        body: Params(user)
    }).then(r => r.json())
    console.log(res);
}