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

我正在尝试将我的应用程序的构造函数对象设置为在单击应用程序中的按钮时从 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);
      });
  }
}

任何帮助将不胜感激 :)

谢了,兄弟们

回答1

你做错了期望 axios 返回 value。您还需要在 async 中调用 axios。并且任何 value axios 返回都可以由 test 函数返回。

试试下面的代码。

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

相似文章

随机推荐

最新文章