VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs.

Continuously encountering these two errors:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

and

TypeError: Cannot read property 'get' of undefined.

var owm = new Vue({
  el: '#owm',
  data: {
    debug: true,
    weather: []
  },
  methods: {
    loadWeather: function() {
      this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade', function(data, status, request){
        if(status == 200)
        {
          this.weather = data;
          console.log(this.weather);
        }
      });
    }
  },
  mounted: function () {
    this.loadWeather();
  }
});

After updating the code using vue resource, the errors have disappeared but the data is not being logged in the console, what could be the issue?

Vue.use(VueResource);
var owm = new Vue({
  el: '#owm',
  data: {
    weather: []
  },
  methods: {
    loadWeather: function() {
      this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]', function(data, status, request){
        if(status == 200)
        {
          this.weather = data;
          console.log(this.weather);
        }
      });
    }
  },
  mounted: function () {
    this.loadWeather();
  }
});

UPDATE: This revised code functions as expected, although I'm unsure about the .then function and why it worked with it instead of the callback function.

this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]').then((data) => {
  this.weather = data;
  console.log(this.weather);

Answer №1

After experimenting with a sample on my local machine, I discovered that the $http usage was incorrect. The correct way to handle it is by referring to the documentation and using a then function to handle the promise resolution. Here is the updated code snippet that worked for me:

 loadWeather: function() {
    var self=this;
  this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade').then(function(response){
    if(response.status == "200"){
        console.log(response);
    self.weather = response.data.list[0].weather // use self instead of this
    }


  })

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

Can we create dynamic v-for variables in Vue.js?

<div class="col-3" v-for="n in 5" :key="n"> <h3>Table {{n}}</h3> <draggable class="list-group" :list="`list${n}`" group="people" @change="log"> ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

Integrating custom HTTP headers with window.location.href in an Angular application

I encountered a situation with my Angular app where I needed to redirect it to a non-angular HTML page. My initial thought was to use $window.location.href to achieve this redirection successfully. However, the challenge arose when I realized that my Node. ...

Here is a guide on updating HTML table values in Node.js using Socket.IO

I successfully set up socket io communication between my Node.js backend and HTML frontend. After starting the Node.js server, I use the following code to emit the data 'dRealValue' to the client side: socket.emit ('last0', dRealValue) ...

Utilize JSON parsing to extract and store data into an object

I'm currently working on extracting specific objects from a parsed JSON stored within an object named data.json. var data = { json: '', text: '', welcome: '', q1: '', } let foo = await fetch(spr ...

Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function a ...

Pattern for identifying Google Earth links with regular expressions

I'm attempting to create a regular expression that can validate whether the URL entered by a user in a form is a valid Google Earth URL. For example: https://earth.google.com/web/@18.2209311,-63.06963893,-0.67163554a,2356.53661597d,34.99999967y,358.13 ...

Unable to submit form in Nextjs using react-bootstrap

Instructions To create a registration form, follow these steps: Fill out the form on the register page and then click submit. The react-bootstrap button will trigger the handleSubmit() function using onSubmit={}. Expected vs Actual Outcome I attempted va ...

What is the process for exporting/importing a variable in Node.js?

What is the correct way to export/import a variable in Node.js? I attempted to use export and import methods, but I received an error message stating that it should be a module. After changing the type to module in the JSON file, it then told me that requ ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Introduce a pause interval between successive ajax get calls

I've created a script that uses an ajax GET request when the user reaches near the end of the page. $(function(){ window.addEventListener('scroll', fetchImages); window.addEventListener('scroll', fetchNotifications); }); ...

"Error message: Attempting to access state in getter without it being defined (Vu

Trying to access the status of a stored login session in my Vuex store, I encountered the following error: Uncaught TypeError: Cannot read property 'user' of undefined The Vuex store configuration is as follows: let store = { state ...

Where is the ideal location to store non-component data properties in Vue.js?

Currently, I am in the midst of a Vue.js project where components are predominantly used. However, there are moments when I simply need to incorporate some Vue.js syntax without creating an entire component. Since I am not utilizing the render function as ...

Node.js with ejs supports the inclusion of partials, but sometimes struggles to locate the variable that has been defined in the partial file

This is the code that should be included in the main ejs file: <% const IDP_URL = "http://idp.com:8082"; const SP_ID = "testing"; const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw=="; const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs"; const L ...

What is the response of Express when it encounters numerous identical asynchronous requests from the same origin?

Currently, I am utilizing Express.js for my project. There is an async function that performs a task that can take anywhere from 20 to 30 seconds to complete. Once the task is done, it increases a user's counter in the database. However, users are req ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Issue with setting state in useEffect causing an infinite loop due to either linter warning or user error

In its current state, my component appears as follows: const { listOfStuff = [{name:"john"},{name:"smith"}] } = props const [peopleNames, setPeopleNames] = useState([]) useEffect(() => { listOfStuff.forEach(userName => { setPeopleNames(people ...

Error in code - message gets sent immediately instead of waiting for timeout to occur

There seems to be an issue with the code where the message is sent instantly instead of waiting for the specified timeout duration. Based on the code, it should wait for the time mentioned in the message. I'm puzzled as to why it's not functioni ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...