2017-04-20 50 views
0

我正在开发没有任何框架的简单应用程序。如何从简单的ES6应用程序进行Http操作

我该如何做简单的Http请求(get/post)?

我了解的XMLHttpRequest():

var xhr = new XMLHttpRequest(); 

xhr.open('GET', 'phones.json', false); 

xhr.send(); 

if (xhr.status != 200) { 

    alert(xhr.status + ': ' + xhr.statusText); 
} else { 
    alert(xhr.responseText); 
} 

但也许有另一种方式?

  • 请不要任何图书馆。

回答

1

嗯,据我所知,在es6 specifications没有什么改变了XMLHttpRequest API以使它更容易,所以这对你的问题来说不是问题。

你还是得写上几行,使之更加“ES6风格”,像promisifying它例如like here

const request = (params) => { 
    return new Promise((resolve, reject) => { 
     const xhr = new XMLHttpRequest(); 
     xhr.open(params.method || "GET", params.url); 
     if (params.headers) { 
      Object.keys(params.headers).forEach(key => { 
       xhr.setRequestHeader(key, params.headers[key]); 
      }); 
     } 
     xhr.onload =() => { 
      if (xhr.status >= 200 && xhr.status < 300) { 
       resolve(xhr.response); 
      } else { 
       reject(xhr.statusText); 
      } 
     }; 
     xhr.onerror =() => reject(xhr.statusText); 
     xhr.send(params.body); 
    }); 
}; 
相关问题