Skip to content

Instantly share code, notes, and snippets.

@chiehwen
Last active November 20, 2017 04:36
Show Gist options
  • Save chiehwen/7027598681c0f481cc011b51d73d31de to your computer and use it in GitHub Desktop.
Save chiehwen/7027598681c0f481cc011b51d73d31de to your computer and use it in GitHub Desktop.
class getCountry {
getCountry() {
// Return a new promise.
return new Promise((resolve, reject) => {
// Do the usual XHR stuff
const xhr = new XMLHttpRequest();
const url = “https://freegeoip.net/json/”
xhr.overrideMimeType(“application/json”);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status >= 200) {
// Resolve the promise with the response text
resolve(console.log(JSON.parse(xhr.responseText).country_name));
} else {
reject({
status: this.status,
statusText: xhr.statusText,
});
}
};
// Handle network errors
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.onloadend = function () {
if (xhr.status === 404) {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.open(“GET”, url, true);
// Make the request
xhr.send();
});
}
}
getCountry.install = (Vue) => {
Vue.prototype.$get = new getCountry().getCountry;
};
export default getCountry;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment