axios簡單使用


介紹

我在使用vue的時候使用到了axios,vue 1.0的版本作者推薦使用vue-resource,到了vue 2.0作者建議使用axios,此篇文章只是我在使用axios時候做的筆記,我遇到的一個些坑,如需查看axios詳細api的使用文檔請看官網https://www.npmjs.com/package/axios

Get,Delete,Head簡單使用

get(url: string, config?: AxiosRequestConfig): AxiosPromise;
delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
head(url: string, config?: AxiosRequestConfig): AxiosPromise

這三個方法使用方式屬於同一類型,Get方法使用示例如下,其他兩個同理

 1 // Make a request for a user with a given ID 
 2 axios.get('/user?ID=12345')
 3   .then(function (response) {
 4     console.log(response);
 5   })
 6   .catch(function (error) {
 7     console.log(error);
 8   });
 9  
10 // Optionally the request above could also be done as 
11 axios.get('/user', {
12     params: {
13       ID: 12345
14     }
15   })
16   .then(function (response) {
17     console.log(response);
18   })
19   .catch(function (error) {
20     console.log(error);
21   });

Post,Put,Patch簡單使用

1 post(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;
2 put(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;
3 patch(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;

這三個方法使用方式屬於同一類型,Post方法使用示例如下,其他兩個同理:

 axios.post(url,JSON.stringify(requestdata),{ headers: { 'Content-Type': 'application/json' },data:{}}).then(function (response) {
     console.log(response);
   })
   .catch(function (error) {
     console.log(error);
   });

這里需要注意的是data:{} 必須添加這個,即使data里面是空,headers是添加http表頭的

axios post上傳表單的時候,需要注意的是 headers: { 'Content-Type': 'application/x-www-form-urlencoded'  這個值,否則后台是接收不到值的

 var formData = new FormData();
 formData.append('file', this.$refs.fileData['files'][0], this.$refs.fileData['files'][0].name);
 formData.append('applicationName', this.form.applicationName);

 axios.post(url, formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
                    .then(response => {
                        console.log(res.data)
                    })
                    .catch(error => {
                        console.log(error)
                    });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM