[Vuejs]-I can not get user's ip address in VueJs

2👍

Parsing the response from CloudFlare’s trace API isn’t super easy since it is not JSON.

I would use a custom response transformer to parse the data into something usable.

Assuming you want to set the ipAddress in local storage only if it’s not there already, try this

methods: {
  async getIpAddress () {
    if (!localStorage.getItem("ipAddress")) {
      const { data: { ip } } = await this.$axios.get("https://www.cloudflare.com/cdn-cgi/trace", {
        responseType: "text",
        transformResponse: data =>
          Object.fromEntries(data.trim().split("\n").map(line => line.split("=")))
      })
      localStorage.setItem("ipAddress", ip)
    }
  }
}
👤Phil

2👍

As above url have cors issue i have come up with new url try this

getIpAddress() {
    this.$axios.get("http://ipinfo.io/json").then(({ data }) => {
    localStorage.getItem("ipAddress")? "" : localStorage.setItem("ipAddress", data.ip);
    });
},

Leave a comment