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

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

我试图将我的应用程序的构造函数对象设置为在我的应用程序中单击按钮时从 axios 请求做出的响应,但我一直收到此错误

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

我猜这是一个范围界定问题,但我不知道如何解决它?

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

任何帮助将不胜感激:)

谢谢 盖伊

你期望 axios 达到 return 值是错误的。您还需要在 async 中进行 axios 调用。并且任何值 axios return 都可以通过 test 函数 return

试试下面的代码。

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