1. ホーム
  2. javascript

[解決済み] AxiosのAPIからデータを返す

2022-12-20 13:52:37

質問

Node.JSアプリケーションを使用して、APIリクエストを作成および受信しようとしています。それは、受け取ったAPIコールから受け取ったデータでAxiosを使用して別のサーバーに取得要求を行います。2番目のスニペットは、スクリプトがコールインからデータを返すときです。実際に受け取ってコンソールに書き込みますが、2つ目のAPIで送り返すことはありません。

function axiosTest() {
    axios.get(url)
        .then(function (response) {
            console.log(response.data);
            // I need this data here ^^
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
}

...

axiosTestResult = axiosTest(); 
response.json({message: "Request received!", data: axiosTestResult});

私はこれが間違っていることを認識しています。私がそこからデータを得ることができる唯一の方法は、console.logを通してであるようですが、それは私の状況では役に立ちません。

どのように解決するのですか?

この問題は、オリジナルの axiosTest() 関数がプロミスを返さないことです。以下、わかりやすくするために説明を拡張します。

function axiosTest() {
    // create a promise for the axios request
    const promise = axios.get(url)

    // using .then, create a new promise which extracts the data
    const dataPromise = promise.then((response) => response.data)

    // return it
    return dataPromise
}

// now we can use that data from the outside!
axiosTest()
    .then(data => {
        response.json({ message: 'Request received!', data })
    })
    .catch(err => console.log(err))

この関数はより簡潔に書くことができます。

function axiosTest() {
    return axios.get(url).then(response => response.data)
}

あるいはasync/awaitで。

async function axiosTest() {
    const response = await axios.get(url)
    return response.data
}