Last active
November 20, 2017 04:36
-
-
Save chiehwen/7027598681c0f481cc011b51d73d31de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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