I am having difficulty retrieving the user's IP address in VueJs

Here is the code snippet:

    Vue.mixin(windowMixin)
    export default {
    name: "App",

    methods: {
        getIpAddress(){

            localStorage.getItem('ipAddress') ? '' : localStorage.setItem('ipAddress', Response.data);
            this.$axios.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) {
                console.log(data)
                })
    },
    mounted() {
        this.getIpAddress();
    }
};

The outcome indicates that I am saving user's IP address as "undefined". Can someone please assist me with this issue? I am new to Frontend development.

Answer №1

Dealing with the response from CloudFlare's trace API can be a bit tricky as it doesn't come in JSON format.

A potential solution could involve using a customized response transformer to make the data more manageable.

If your goal is to store the ipAddress in local storage only if it's not already present, consider implementing the following:

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)
    }
  }
}

Answer №2

Due to a CORS issue with the previous URL, I have found a new URL that should work. Please use this new URL:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Encountering the error "ReferenceError: __extends is not defined" is a common issue when modifying the rollup.config.js commonjs function in projects that use the ReactJS library

Currently, I am involved in a project and there is also a library project containing all the common components used throughout. Within this library, I had to integrate a component that relies on materialUI. However, upon trying to export this component, I ...

Storing segments of URL data for future use in React applications

Is there a way to extract information from a URL? I wish to utilize the appended details in this URL http://localhost:3000/transaction?transactionId=72U8ALPE within a fetch API. My goal is to retrieve the value 72U8ALPE and store it either in a state var ...

Getting the Height and Width of an Image during the upload process in a React application

Can anyone help me with retrieving the Image Height and Width during image upload? I have attempted the following code, but it always gives me 0 0: const uploadedImage = e.target.files[0]; var image = new Image(); image.src = uploadedImage; console.log( ...

An error was encountered when trying to read property '0' of an undefined object in a for loop

Currently, I am working on a project to create a mastermind game. Everything is progressing smoothly, except for one issue that keeps popping up - I keep encountering the error: "uncaught typeerror cannot read property '0' of undefined." fun ...

How to retrieve a JSON value without a key using jQuery

I am struggling to fetch JSON using jQuery. If anyone can help me figure out the mistake in my code that would be greatly appreciated. The data.json file contains { "value1", "value2", "value3", "value4" } Here is my jQuery code $.getJSON( "data.js ...

The function of slidetoggle is malfunctioning when clicked

I currently have two dynamic containers with one displaying grouped boxes, quantities, and totals, while the other shows detailed information. Both container values are added dynamically at runtime. By default, the grouping container is displayed on the p ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

Performing multiple http requests in a loop and combining the retrieved data using AngularJS

I am currently working with a piece of source code that looks like this: var projectPromises = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456'); $q.all([projectPromises]).then(function(data) { console.log(data); ...

The function .innerHTML is not functioning correctly, at least in my opinion

When I utilize .innerHTML to insert text into a textarea, the script stops functioning if I manually begin editing the text in the textarea. Here is the code snippet: (function($){ addPort = function(name) { switch(name) { case 'name1': ...

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

Modified the object path and updated the Dirty stages for nested objects within Vue state

Imagine having an object that contains arrays of objects in some properties. Whenever changes are made to any field, whether it's within an object in an array or the main object itself, you want to mark that object as "dirty" using a code snippet like ...

I need clarification on some basic concepts about ajax - Can you help?

Could someone please assist me in clarifying a concept? Currently, I am utilizing the colorbox plugin to load an external html snippet (which is functioning correctly). However, my jquery selectors are unable to detect the newly loaded html. Is this the co ...

A div positioned in front of a centrally-located div

Managing a website with numerous headlines can be a challenge. When a user clicks on a headline, a button located 10px to the left of the headline should appear. However, the catch is that the headlines must always remain centered, regardless of whether th ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Navigating from an error page to the homepage with Next.JS 13: A quick and easy guide

I'm currently working on implementing a feature that allows users to easily go back to the main page from an error page within the app folder. Specifically, in my weather app project, if a user enters an incorrect city, they should have the option to ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Rearrange the entire div container by simply dragging and dropping it. (Shift the Pop-up Modal dialog box)

How can I make a Modal pop-up draggable and change the color of the "Ok" and "Cancel" buttons on hover using a single CSS class? .hidModal{ position: fixed; font-family: Arial, Helvetica, sans-serif; top: 0; right: 0; bottom: 0; ...