【问题标题】:How to make Http operations from simple ES6 application如何从简单的 ES6 应用程序进行 Http 操作
【发布时间】:2017-09-16 17:10:45
【问题描述】:
我正在开发没有任何框架的简单应用程序。
如何进行简单的 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 );
}
但也许还有其他方法?
【问题讨论】:
标签:
json
http
ecmascript-6
xmlhttprequest
【解决方案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);
});
};