初步了解XMLHttpRequest对象和http函数的封装

目录

  • 构造器

    • var xhr = new XMLHttpRequest()
  • XMLHttpRequest属性

      • xhr.ontimeout:         超时时间;0为永不超时
      • xhr.readystate:          HTTP请求状态

    当前阶段 状态码
    new XMLHttpRequest() 0
    xhr.open() 1
    请求发出,未收到响应头 2
    响应头接收ok,开始接收响应体 3
    响应体接收完成 4
    • xhr.status:            返回值状态码
      •   

        1xx  信息

      • 2xx  成功
        • 200:请求成功
      • 3xx  重定向
        • 304:重定向到:使用缓存
      • 4xx  客户端错误
        • 404:客户端错误
      • 5xx  服务器错误
        • 500:服务器遇到未知错误
    • xhr.statusText:          返回值状态码描述
      • xhr.status === 200时,xhr.statusText === 'ok'
    • xhr.responseText:     请响应体body
      • 默认值:''
      • 默认编码:Unicode UTF-8
    • xhr.responseXML: 对请求的响应,解析为XML并作为Doucment对象返回
  • XMLHttpRequest方法

    方法                                           解释
    xhr.abord() 关闭这个请求,将readyState重置为0
    xhr.open() 打开一个HTTP请求
    xhr.send() 发送HTTP请求
    xhr.setRequestHeader() 向一个打开但未发送的请求设置或添加一个http请求头部
    xhr.getAllResponseHeaders() 将HTTP响应头作为未解析的字符串返回
    xhr.getResponseHeder() 返回指定的HTTP响应头部的值

     

  • XMLHttpRequest事件

    • onreadystatechange:当readyState改变时
    • ontimeout:请求超时
    • onloadend:请求结束
    • onerror:请求出错
  • 一个案例

    let xml = new XMLHttpRequest();
    xml.timeout = 0;  //设置超时时间:0永不超时
    /**
     * xml.open(method, url, async, username?, password?)  
     *    打开一个请求,但不发送
     *    会重置readyState = 1、responseText、responseXML、status 以及 statusTex恢复默认值
     *    删除之前指定的所有的请求头部和响应头部
     */
    xml.open('get', 'http://localhost:3000/api1')
    
    /**
     * xml.send(body?: string)
     *    请求体
     *    post|put:string
     *    其他:null,或者不传
     * 
     *    发送open()时指定的mehods、URL、认证资格
     *    指定的setRequestHeader()
     *    传递body参数
     * 
     *    请求发出,send()将readyState设置为2,并处触发onreadystatechange
     */
    xml.onprogress = function () {
      console.log( 111 )
    }
    xml.send()
    xml.onloadend = function () {
      console.log( 'loadend...' )
    }
    xml.onerror = function () {
      console.log( 'onerror...' )
    }
    xml.onreadystatechange = function () {
      console.log( xml, xml.responseText )
      if(xml.readyState === 4){
        if(xml.status === 200){
          console.log( xml.responseText )
        }
      }
    }
  • 封装http请求函数

     /**[接口域名] */
     const BASE_URL = 'http://localhost:3000'
    
     export default http = {
       /**
        * [query方法传参]
        */
       get (route, params) {
         return this.request('GET', this.getUrl(route, params))
       },
       /**
        * [body方法传参]
        */
       post (route, params) {
         return this.request('POST', this.getUrl(route), JSON.stringify(params))
       },
       /**
        * [body方法传参]
        */
       put (route, params) {
         return this.request('PUT', this.getUrl(route), JSON.stringify(params))
       },
       /**
        * [query方法传参]
        */
       delete (route, params) {
         return this.request('DELETE', this.getUrl(route, params))
       },
       /**
        * [body方法传参]
        */
       patch (route, params) {
         return this.request('PATCH', this.getUrl(route), JSON.stringify(params))
       },
       request (method, url, params) {
         return new Promise ((resolve, reject) => {
           params = typeof params === 'undefined' ? null : params
           const xhr = new XMLHttpRequest();
           xhr.open(method, url);
           xhr.send(params);
           xhr.onreadystatechange = function () {
             if( xhr.readyState === 4 ) {
               if( xhr.status === 200 ){
                 resolve(JSON.parse(xhr.responseText))
               } else {
                 new Error('请求失败,错误码为:' + xhr.status + '; 错误状态:' + xhr.statusText)
               }
             } else {
               new Error('请求失败')
             }
           }
         })
       },
       /**
        * [获取URL]
        */
       getUrl (route, params) {
         const reg = /^http|https/
         let url = ''
     
         if(!reg.test(route)){
           url = BASE_URL + route
         } else {
           url = route
         }
     
         return typeof params !== 'undefined' ? this.stringifyUrl(url, params) : url
       },
       /**[拼接参数] */
       stringifyUrl (url, params) {
         let paramsStr = ''
     
         Object.keys(params).forEach((key, i, arr) => {
           if(i < arr.length-1){
             paramsStr += key + '=' + params[key] + '&'
           } else {
             paramsStr += key + '=' + params[key]
           }
         })
     
         if(url.indexOf('?') > -1){
           url += '&' + paramsStr
         } else {
           url += '?' + paramsStr
         }
     
         return url
       }
     }

猜你喜欢

转载自www.cnblogs.com/wenwenwei/p/10438309.html
今日推荐