axios的增删查改

129 阅读1分钟

get请求

// 写法1
function (url) {
    axios.get(url).then((res) => console.log(res))
}
// 写法2
function (url) {
    axios({
        url: url + "/12" , // 通过url地址携带参数id
        method: "get"
    }).then((res) => console.log(res))
}
// 写法3
function (url) {
    axios({
        url, // url:url对象的简写 
        method: "get",
        params: {
            address: "中国新疆"
        }
    }).then((res) => console.log(res))
}

// get请求,封装方法
const get = (url, params) => {
    return axios({
        method: "get",
        url,
        params
    })
}
// 使用
async function fn() {
    let res = await get("http://127.0.0.1:9090/users", { address_like: "新疆" })
    console.log(res);
}

post方法

// 写法一
function fn() {
    axios.post("http://127.0.0.1:9090/users", {
        name: "刘耀文",
        age: 18,
        sex: "男",
        address: "四川"
    }).then((response) => console.log(response))
}
// 写法二
function fn() {
    axios({
        url: "http://127.0.0.1:9090/users",
        method: "post",
        data: {
            name: "张三",
            age: 20,
            sex: "男",
            address: "湖南"
        }
    }).then(function (res) {
        console.log(res);
    })
}

// post请求,封装方法
const post = (url, data) => {
    return axios({
        method: "post",
        url,
        data
    })
}
async function fn() {
    let res = await post("http://127.0.0.1:9090/users", {
        name: "赵六",
        age: 30,
        sex: "男",
        address: "河北"
    })
    console.log(res);
}

delete 删除

function fn() {
    axios({
        url: "http://127.0.0.1:9090/users/14",  //通过url携带id进行删除
        method: "delete"
    }).then((res) => console.log(res))
}

修改(2个)

// 修改
// 根据id修改  ==>  /12
// 写法1 patch() 部分修改
function fn() {
    axios({
        url: "http://127.0.0.1:9090/users/12",
        method: "patch",
        data: {
            name: "李四",
            age: 50
        }
    }).then((res) => console.log(res))
}
// 写法二 put()全部修改
function fn() {
    axios({
    url: "http://127.0.0.1:9090/users/13",
    method: "put",
    data: {
        name: "王五", age: 90
    }
    }).then((res) => console.log(res))
}