4

I have a web page that is using the Axios Http Client. In my web page, I'm getting my location using the browser's geolocation feature. When my location is obtained, I want to send that location, along with other data. To do this, I've built data object like this:

navigator.geolocation.getCurrentPosition(
  function(position) { 
    var data = {
      id: 1,
      user:'me',
      location: position
    };
  })
;

I then try to send the data via Axios like this:

axios.put('/my-endpoint', data, options)
    .then(function(res) {
      console.log('success');
      console.log(res);
    })
;    

I get a successful response back from this request. However, it's a false positive. When I look at the logs, it's weird. I can see that the location property is an empty object. So, I did a console.log in the browser and I can see that location is properly set. But when I send it via Fiddler, I notice that it's not there. It's just an empty object when it goes across the wire. How?

I suspect there is some setting or something else I have to do to send a nested JavaScript object over the network. But I don't see anything. What am I doing wrong? I've made a basic JSFiddle here with this code..

1 Answer 1

1

It looks like your variable data is out of scope when you are trying to send it. In the example you've given data is local variable of that closure which means it is destroyed when the callback completes. To get around this you need to declare data outside of that function where it will be visible to axios as well. You can still assign to it inside the callback, you have to actually but you should declare it above.

Sign up to request clarification or add additional context in comments.

3 Comments

the variable data is in scope. It looks out of scope because of how I phrased the question. But, in my actual code the axios call happens right after the var data line.
Is it only for the location property? Are user and id going through ok?
It's only the location property that is showing this behavior. user and id are going through ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.