![見出し画像](https://assets.st-note.com/production/uploads/images/117934328/rectangle_large_type_2_d06750f9cfdf8427ba3fab47c49353c6.jpeg?width=1200)
Velo 第48回 fetch( ) を使う
fetch( ) 関数はHTTPおよびHTTPSリクエストを送信するためのプロミスベースの API です。
コンテンツが存在する URL を引数にして呼び出し、戻り値はwixFetchResponseというプロミスです。
それが解決すればコンテンツが返されます。
ここでは Wix Reference 掲示のエンドポイントから世界の「挨拶」をゲットします。
そのために先ずバックエンドに新規Webモジュールを作り、ファイル名を getGreeting.jsw とします。
![](https://assets.st-note.com/img/1696236212752-lMDSIdrM74.png?width=1200)
このファイルでfetch( ) 関数を使います。
URL は Velo Reference に掲載のあったエンドポイントです。
ここには世界の「挨拶のリスト」があり、HTTPリクエストがあればAPI がランダムに「挨拶」を選んでレスポンスするようです。
選ばれた挨拶のオブジェクトは2つのプロパティ message、language を持ちます。
以下のコードではレスポンスが正常なら挨拶を JSON で返すように指示しています。
万一失敗ならテキストで「すいません」を返します。
![](https://assets.st-note.com/img/1696236226983-3M9SFQSmO3.png?width=1200)
プレイボタンをクリックして実行させると languageが 'French'、message が 'Bonjour monde!' であるオブジェクトが返っています。
実験成功です。
![](https://assets.st-note.com/img/1696236239881-TutK8jZXMz.png?width=1200)
ページにはクリックイベントを発生させるボタン(fetchButton) と挨拶、言語を 表示させるテキストを配置します。
![](https://assets.st-note.com/img/1696236307305-OTBE9dHgBe.png)
コードページの冒頭で Webモジュールから関数 getRandomGreeting( ) をインストールしています。
次に、ボタン(fetchButton)のクリックイベントを非同期で設定しています。その中で、戻り値がオブジェクトなら挨拶を表示させます。
そうでなければ「すいません」が表示されます。
![](https://assets.st-note.com/img/1696253777128-O3tUfdQwPG.png?width=1200)
プレビューの結果です。
![](https://assets.st-note.com/production/uploads/images/117843325/picture_pc_4205ff23ac5d589136112abaf9487c91.gif?width=1200)
Velo Developer certification の4択問題に fetch( ) の引用があります。いくつかご紹介します。
Which of the following can you use to interact with external sources using Velo? Select all answers that apply.
wix-fetch
npm modules
CURL
$.ajax( )
How do you send a POST request using wix-fetch?
Define POST as the method in the fetch options.
No need to. POST is already the default method when using wix-fetch.
wix-fetch is only for GET requests. You need to use wix-send instead.
Use wix-fetch in the backend, and then it defaults to POST.
Which of the following statements about wix-fetch is correct?
The fetch() function retrieves a JSON resource from network. It returns a Promise that resolves to a JSON object representing the response to the request.
The wix-fetch() function retrieves an XML resource from the network.It returns Promise that resolves to an object representing the response to the request.
In order to use wix-fetch in the frontend you need to use $w.ajax() .
The fetch() function fetches an HTTPS resource from the network. It returns a Promise that resolves to a WixFetchResponse.
![](https://assets.st-note.com/img/1696319942888-vH5ZBS3lsZ.jpg)
Velo開発のご依頼はこちら
この記事が気に入ったらサポートをしてみませんか?