簡體   English   中英

使用 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 返回值。 您還需要在async中進行 axios 調用。 並且 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);
            });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM