天天看點

使用ajax,fetch,axios請求接口

原生ajax請求資料五步驟

//步驟一:建立XMLHTTPRequest對象
   let xhr = new XMLHttpRequest()
 //步驟二:設定請求的類型,請求的url
    xhr.open('get', 'https://api.github.com/search/users?q=owen')
 //步驟三:發送請求
    xhr.send()
    xhr.timeout = 2000 //逾時設定
    xhr.ontimeout = ()=>{//請求逾時回調}
    xhr.onerror = () =>{//網絡異常回調}
    xhr.abort() //取消請求
 //步驟四:使用事件onreadystatechange進行函數回調
    xhr.onreadystatechange = function () {
  //步驟五判斷狀态嗎響應資料
      if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
               console.log(xhr.response)
          }
    }
           

使用fetch請求接口資料

fetch('https://api.github.com/search/users?q=owen',{
        method:'',
        headers:{},
        body:''
        }).then(res => {
        /*此處fetch請求的資料需要使用res原型上對應的方法去解析
              json()  
              blob()
              arrayBuffer()
              text()
              formData()
            */
            return res.json()
        }).then(res => {
            console.log('請求成功',res)
        }).catch(err => {
            console.log('請求錯誤',err)
        })
           

axios請求接口資料

axios.get(`/gitHub/search/users?q=owen`).then(res=>{
     console.log('請求成功',res)
 }).catch(err=>{
	  console.log('請求錯誤',err)
 })
           

或者

axios({
   method:'', //請求方式
   url:'',
   headers:{}
   data:{}
})
           

繼續閱讀