简体   繁体   中英

Can't set my Aurelia apps response when making an API Request with Axios

I am trying to set my App's constructor object to the response made from an axios request when clicking on a button in my app but I keep getting this error

app.js:25 TypeError: Cannot set properties of undefined (setting 'response'): at app.js:22:17

I am guessing it is a scoping issue but I have no idea how to fix it ?

import Axios from "axios";
const axios = require("axios");

export class App {
  constructor() {
    this.response = [];
    this.testing = "";
  }

  test() {
    const options = {
      method: "GET",
      url: "https://omgvamp-hearthstone-v1.p.rapidapi.com/cardbacks",
      headers: {
        "X-RapidAPI-Host": "omgvamp-hearthstone-v1.p.rapidapi.com",
        "X-RapidAPI-Key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      },
    };

    Axios.request(options)
      .then(function (response) {
        return (this.response = response.data[0]);
      })
      .catch(function (error) {
        console.error(error);
      });
  }
}

Any help would be greatly appreciated :)

Thanks Guy

You are doing it wrong expecting axios to return value. Also you need make axios call in async . And whatever value axios return can be return by test function.

try below code.

export class App {
    constructor() {
        this.response = [];
        this.testing = "";
    }

    async test() {
        const options = {
            method: "GET",
            url: "https://omgvamp-hearthstone-v1.p.rapidapi.com/cardbacks",
            headers: {
                "X-RapidAPI-Host": "omgvamp-hearthstone-v1.p.rapidapi.com",
                "X-RapidAPI-Key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            },
        };

        this.response = await axios.request(options)
            .then(function (response) {
                return response.data[0];
            })
            .catch(function (error) {
                console.error(error);
            });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM