[解決済み] 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
}
関連
-
[解決済み] 配列から特定の項目を削除するにはどうすればよいですか?
-
[解決済み] cURLでJSONデータをPOSTするにはどうすればよいですか?
-
[解決済み] AngularJSでデータバインディングはどのように機能するのですか?
-
[解決済み] Node.jsを完全にアンインストールして、最初から再インストールする方法 (Mac OS X)
-
[解決済み] REST APIからデータを取得しようとしたときに、要求されたリソースに'Access-Control-Allow-Origin'ヘッダーが存在しない。
-
[解決済み] URLクエリパラメータを含むHTTP POST -- 良いアイデアかどうか?
-
[解決済み] AxiosのHTTPエラーからステータスコードを取得するにはどうすればよいですか?
-
[解決済み】オブジェクトからプロパティを削除する(JavaScript)
-
[解決済み] node.jsで文字列のsha1ハッシュを取得するにはどうすればよいですか?
-
[解決済み] Javascriptで動的に命名されたメソッドを呼び出すにはどうすればよいですか?
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
[解決済み] JSのDateからDay名
-
[解決済み] Google maps API V3 - 同一地点に複数のマーカーを設置する。
-
[解決済み] Angularjs - 現在の日付を表示する
-
[解決済み] Chart.jsを使ってドーナツチャートの中にテキストを追加するには?
-
[解決済み] TypeScriptのdeclare classとinterfaceの違いとは?
-
[解決済み] JavaScriptで:hoverのCSSプロパティを変更する
-
[解決済み] javascriptで文字列から関数を作成する方法はありますか?
-
[解決済み] $.ajax実行中にローディングイメージを表示する
-
[解決済み] jQueryのバージョン1、バージョン2、バージョン3の違いは何ですか?[クローズド]
-
[解決済み] JavaScriptデータフォーマット/プリティプリンタ