欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue2利用Axios發(fā)起請求的詳細(xì)過程記錄

 更新時間:2021年12月26日 12:14:09   作者:Java小學(xué)生丶  
有很多時候你在構(gòu)建應(yīng)用時需要訪問一個API并展示其數(shù)據(jù),做這件事的方法有好幾種,而使用基于promise的HTTP客戶端axios則是其中非常流行的一種,這篇文章主要給大家介紹了關(guān)于Vue2利用Axios發(fā)起請求的詳細(xì)過程,需要的朋友可以參考下

前言

當(dāng)你看到該文章時希望你已知曉什么是跨域請求以及跨域請求的處理,本文不會贅述

本文后臺基于Springboot2.3進(jìn)行搭建,Controller中不會寫任何業(yè)務(wù)邏輯僅用于配合前端調(diào)試

Controller中使用的R.success為本人封裝的工具類,代碼在文末

Axios的安裝和配置

在項(xiàng)目目錄下執(zhí)行命令安裝axios

npm install -S axios

打開src路徑下的main.js文件,在文件中引入axios依賴并掛載到vue全局屬性中

// 引用axios依賴
import axios from 'axios'

// 掛在到vue中,這里將axios掛載為request,在組件中就可以使用this.request來調(diào)用axios了
Vue.prototype.request = axios;

發(fā)起GET請求調(diào)用的是axios中的get方法,點(diǎn)進(jìn)去可以看到該方法接收了url和config兩個對象

發(fā)起簡單GET請求

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/list")
    public R list() {
        return R.success("用戶列表查詢成功!");
    }
}
<template>
    <div id="index">
        <button @click="selectList">查詢用戶</button>
    </div>
</template>
<script>
export default {
    name: "index",
    methods: {
        selectList() {
            // 簡單GET請求只需要傳入URL就可以實(shí)現(xiàn)
            this.request.get("http://localhost:8000/user/list").then(res => {
                console.log("res", res);
            }).catch(e => {
                console.log("e", e);
            })
        }
    }
}
</script>
<style></style>

發(fā)起簡單GET請求并攜帶參數(shù)

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/get")
    public R get(String id) {
        return R.success("用戶獲取成功!");
    }
}
selectOne() {
    let config = {
        params: {id: "1"}
    }
    // url后面跟上config對象,config對象中的params屬性對應(yīng)的就是請求參數(shù)
    this.request.get("http://localhost:8000/user/get", config).then(res => {
        console.log("res", res);
    }).catch(e => {
        console.log("e", e);
    })
},

發(fā)起POST請求

發(fā)起POST請求調(diào)用的是axios中的post方法,點(diǎn)進(jìn)去可以看到該方法的參數(shù)列表有三個對象

發(fā)起簡單POST請求

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/save")
    public R save() {
        return R.success("用戶添加成功!");
    }
}
save() {
    // 發(fā)送簡單POST請求與簡單GET請求雷同,只需要將get方法修改為post方法即可
    this.request.post("http://localhost:8000/user/save").then(res => {
        console.log("res", res);
    }).catch(e => {
        console.log("e", e);
    })
},

發(fā)起POST請求并攜帶參數(shù)(一)

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 一般發(fā)起POST請求都是將參數(shù)放在請求體中,然后在通過@RequestBody進(jìn)行解析的
     * 這里我就不創(chuàng)建實(shí)體類了,直接使用Map集合來接收一下
     */
    @PostMapping("/save")
    public R save(@RequestBody Map<String, String> data) {
        return R.success("用戶添加成功!")
                .setAttribute("name", data.get("username"))
                .setAttribute("pwd", data.get("password"));
    }
}
save() {
    let data = {
        username: "Java小學(xué)生丶",
        password: "123456789"
    }
    // 當(dāng)看到參數(shù)列表的時候應(yīng)該就能猜出來,直接將對象放在第二個參數(shù)上就可以
    // 需要注意的是這種方法攜帶的參數(shù)是放在請求體中的
    this.request.post("http://localhost:8000/user/save", data).then(res => {
        console.log("res", res);
    }).catch(e => {
        console.log("e", e);
    })
},

發(fā)起POST請求并攜帶參數(shù)(二)

上面說直接使用data傳遞參數(shù)是放在請求體中的,需要后端使用@RequestBody才能取到,這里將參數(shù)改為路徑參數(shù)進(jìn)行提交

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/save")
    public R save(String username, String password) {
        return R.success("用戶添加成功!")
                .setAttribute("name", username)
                .setAttribute("pwd", password);
    }
}
save() {
    let config = {
        params: {
            username: "Java小學(xué)生丶",
            password: "123456789"
        }
    }
    // 這里不使用data,改用config進(jìn)行傳參,還是將對象封裝為params進(jìn)行傳遞
    this.request.post("http://localhost:8000/user/save", null, config).then(res => {
        console.log("res", res);
    }).catch(e => {
        console.log("e", e);
    })
},

上傳文件測試

除開GET、POST請求之外,還有PUT、DELETE等等類型的請求,這里就不一一測試了,來了解一下上傳文件

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/upload")
    public R upload(MultipartFile file, String fileName) {
        // file對象就是接收到的文件,針對文件的處理邏輯省略不寫...
        return R.success("文件上傳成功!")
                .setAttribute("fileName", fileName);
    }
<template>
    <div id="index">
        <!-- input:file 用于選擇文件,選擇文件后觸發(fā)change事件調(diào)用fileChange方法 -->
        <input type="file" id="file" @change="fileChange" />
        <!-- 執(zhí)行上傳文件的方法 -->
        <button @click="upload">點(diǎn)擊上傳</button>
    </div>
</template>

<script>
export default {
    name: "index",
    data() {
        return {
            file: null
        }
    },
    methods: {
        fileChange(event) {
            // 當(dāng)選擇了某個文件后會觸發(fā)該方法,將文件對象存放到file中
            this.file = event.target.files[0];
        },
        upload() {
            // 創(chuàng)建一個FormData對象,將file放進(jìn)去,也可以放一些其他參數(shù)
            let data = new FormData();
            data.append('file', this.file);
            data.append('fileName', "11223344.txt");
            // 創(chuàng)建config對象,設(shè)置請求頭類型為multipart/form-data
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }
            // 發(fā)起請求攜帶剛剛創(chuàng)建的對象
            this.request.post('http://localhost:8000/user/upload', data, config).then(res => {
                console.log("res", res);
            })
        }
    }
}
</script>

Axios的config配置

通過觀察可以發(fā)現(xiàn)Axios的請求都會接收一個config對象,可以在node_modules/axios/index.d.ts文件看到該配置的詳細(xì)信息:

配置項(xiàng)有很多,我也是個新人好多沒接觸過,這里就簡單測試幾個其他隨時用隨時查,推薦一個Axios中文網(wǎng)

baseURL

baseURL是個比較常用的屬性,可以針對每個請求設(shè)置根地址,我們在發(fā)起請求時只需要關(guān)注請求路徑即可

<script>
export default {
    name: "index",
    data() {
        return {
            config: {
                baseURL: "http://localhost:8000"
            }
        }
    },
    methods: {
        test() {
            let data = {name: "Java小學(xué)生丶"};
            this.request.post("/user/save", data, this.config).then(res => {
                console.log("res", res);
            });
        },
    }
}
</script>

timeout

timeout也屬于比較常用的配置項(xiàng),用于配置請求的超時時間,單位是毫秒ms,設(shè)置為0代表不設(shè)置超時時間

<script>
export default {
    name: "index",
    data() {
        return {
            config: {
                baseURL: "http://localhost:8000",
                timeout: 5000
            }
        }
    },
    methods: {
        test() {
            let data = {name: "張涵哲"};
            this.request.post("/user/save", data, this.config).then(res => {
                console.log("res", res);
            });
        },
    }
}
</script>

withCredentials

該屬性同樣比較常用,withCredentials的值為bool類型,用于設(shè)置是否允許攜帶Cookie,Axios請求默認(rèn)是不允許攜帶Cookie的,可以通過Controller打印sessionID進(jìn)行測試

<script>
export default {
    name: "index",
    data() {
        return {
            config: {
                baseURL: "http://localhost:8000",
                // 需要服務(wù)端進(jìn)行配合
                withCredentials: true,
                timeout: 5000
            }
        }
    },
    methods: {
        test() {
            let data = {name: "Java小學(xué)生丶"};
            this.request.post("/user/save", data, this.config).then(res => {
                console.log("res", res);
            });
        },
    }
}
</script>

Axios暫時就寫到這里,了解這些日常開發(fā)基本不成問題了,用熟config后可以試著封裝一個工具類

總結(jié)

到此這篇關(guān)于Vue2利用Axios發(fā)起請求的文章就介紹到這了,更多相關(guān)Vue2用Axios發(fā)起請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論