axios-基礎

學習axios以前能夠先搭建一個模擬數據請求服務器:
1、json-server服務器搭建
GitHub:https://github.com/typicode/j...
一、下載json-servernode

npm install -g json-server

二、建立一個db.json複製以下代碼ios

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

三、在db.json同級目錄下執行以下命令git

json-server --watch db.json

image.png
經過訪問提供給咱們的連接,可以模擬獲得請求數據;
例如地址欄訪問:github

http://localhost:3000/posts

能夠獲得以下數據
image.pngajax

2、axios簡介npm

https://github.com/axios/axios

axios是一個基於node的HTTP客戶端,能夠在瀏覽器端向服務器發送ajax請求,也能夠在node端向遠端服務發送http請求。
特色:
一、能夠在瀏覽器make XMLHTTPRequests
二、能夠在node端發送http請求
三、支持Promise API
四、請求響應攔截器
五、對請求和相應數據作轉換
六、取消請求
七、自動將請求數據轉換成json數據
八、客戶端支持防護XSRFjson

3、axios配置
配置方法有不少,通常項目中使用npm和yarn安裝axios

npm install axios
yarn add axios

學習階段能夠使用CDN方式直接使用script標籤引入瀏覽器

<script src= 'http://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'></script>

國內服務器能夠使用bootcdn上的資源服務器

<script src= 'https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js
    '></script>

4、axios基本使用
一、發起一個GET請求

btn[0].onclick = ()=>{
    axios({
        method: 'GET',
        url: 'http://localhost:3000/posts'
    }).then(res=>{
        console.log(res) //{data: Array(1), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
        console.log(res.data)//[{ "id": 1, "title": "json-server", "author": "typicode" }]
    })
}

二、發起一個POST請求

btn[1].onclick = ()=>{
    axios({
        method: 'POST',
        url: 'http://localhost:3000/posts',
        data: {
            title: 'Hello Axios',
            author: 'Liane'
        }
    }).then(res=>{
        console.log(res)
    })
}

5、axios的方法
一、axios.request(config)--與axios()的使用方法一致。
二、axios.get(url[,config])--發送GET請求,通常用於獲取數據
三、axios.post(url[,data,config])--發送POST請求,通常用於提交數據和上傳文件。
四、axios.delete(url[,config])--發送DELETE請求,參數能夠放在url上也能夠和post同樣放在請求體中。
五、axios.put(url[,data,config]])--發送PUT請求,對數據所有進行更新。

6、Request Config
config中可設置以下參數:

{
    url: '/posts', //設置請求路徑
    method: 'get', //default,設置請求類型
    baseURL: 'http://localhost:3000', //設定請求的協議和域名等基礎結構,在發起請求時會自動拼接url參數的路徑
    transformRequest:[ //對請求的數據在發起請求前作預處理
        (data,headers)=>{
            return data
        }
    ],
    transformResponse:[ //對請求響應結果作預處理
        (data)=>{
            return data
        }
    ],
    headers: {'X-Requested-Width','XMLHttpRequest'},//配置請求頭信息
    params: { //設定url參數--http://localhost:3000/index/ID:12345
        ID: 12345
    },
    paramsSerializer: (data)=>{//params參數序列號
        return Qs.stringify(params,{arrayFormat:'brackets'})
    },
    data: {  //請求體設置爲對象,請求發起時會自動轉成json格式
        firstName: 'Fred'
    },
    data: 'Country=Barasil&City=Belo',//請求體設置爲字符串,會直接發起請求
    timeout: 1000,//超時時間,若請求發起超過這個時間,則請求會取消,單位爲ms
    widthCredentials: false, //在跨區請求時對cookie的攜帶作設置,值爲false表示不攜帶cookie
    adapter: (data)=>{ //對請求的適配器作設置-設置發送ajax或者在node中發送http請求
        /*...*/
    },
    auth: {
        username:'janedoe',
        password: 's00pers3crept'
    },
    responseType: 'json',
    responseEncoding: 'utf8',
    xsrfCookieName: 'XSRF-TOKEN', // 跨站請求標識,對cookie名字作設置。
    proxy: { //代理
        protocol: 'https',
        host: '127.0.0.1',
        port: 9000,
        auth: {
            username: 'mikeymike',
            password: 'rapunz3l'
        }
  },
    ...
}

7、axios的默認配置

axios.defaults.method = 'GET';//設置默認的請求類型爲GET
axios.defaults.baseURL = 'http://localhost:3000';//設置基礎URL
axios.defaults.timeout = 30000;//設置超時時間

axios({
    url: '/posts'
}).then(res=>{
    console.log(res)
})

8、axios建立實例對象發送請求
在實際開發中,可能有多個服務器分別處理不一樣的請求,所以能夠針對不一樣的服務器建立不一樣的axios實例
語法:axios.create()

cosnt myAxios1 = axios.create({
    baseURL: 'http://xxxx/xxx',
    timeout: 2000
})
//能夠直接調用
myAxios1({url: '/xxx'}).then(res=>console.log(res))
//也能夠使用axios的方法調用
myAxios1.get('/xxx').then(res=>console.log(res))
相關文章
相關標籤/搜索