0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

title.rb

async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data?query=apple");
    
    if (!response.ok) {               // HTTPステータスが 200 系でない場合
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (err) {
    console.error('取得エラー:', err);
    alert('データの取得に失敗しました'); // ユーザーへの通知も可能
  }
}

デバッグ

title.rb
fetch("<<WebAPIのURL>>")
  .then(response => {
    console.log("status:", response.status);   // 実際のステータス数値
    console.log("ok:", response.ok);           // true/false
    console.log("url:", response.url);         // 最終アクセス先のURL
    console.log("headers:", [...response.headers]); // 全レスポンスヘッダ

    return response.text(); // JSONにせずテキストで中身を確認
  })
  .then(text => {
    console.log("body:", text); //  ここでJSONが返っているか確認
  })
  .catch(err => {
    console.error("fetch error:", err);
  });

join()

title.rb
const baseUrl = "api/search?db=1";

// 検索ボタンやセレクトボックスの onchange で呼ぶ関数
async function fetchData() {
  const select1Value = document.querySelector("#select1").value;
  const select2Value = document.querySelector("#select2").value;

  // 配列に条件を追加
  const params = [];
  if (select1Value) params.push(`keyword=${encodeURIComponent(select1Value)}`);
  if (select2Value) params.push(`a=${encodeURIComponent(select2Value)}`);

  // 配列を & で結合して URL を生成
  const apiUrl = baseUrl + (params.length ? "&" + params.join("&") : "");
  console.log("API URL:", apiUrl);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?