简体   繁体   English

使用 Axios 发出 API 请求时无法设置我的 Aurelia 应用程序响应

[英]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我试图在单击我的应用程序中的按钮时将我的应用程序的构造函数对象设置为由 axios 请求做出的响应,但我一直收到此错误

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.你做错了期望 axios 返回值。 Also you need make axios call in async .您还需要在async中进行 axios 调用。 And whatever value axios return can be return by test function.并且 axios 返回的任何值都可以通过test函数返回。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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