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?

【データベースからとってきた情報を確認する方法】

Posted at

フロントエンドがバックエンドからのレスポンスを受け取る処理について

await response.json();
response は、fetch() の結果として得られる HTTP レスポンスオブジェクト。
.json()メソッドを使うことで、レスポンスのボディ部分を JSON 形式として解析し、JavaScript のオブジェクトとして扱えるようにしてる。
await を使っているので、response.json() の処理が終わるまで待機し、その後 data変数に代入しています。(awaitasyncとセット!)

console.log("ログイン成功:", data);
console.log() は、ブラウザの開発ツール(F12 → Console タブ)にデータを出力するための関数。
・"ログイン成功:" というテキストと、data の内容をログに出力します。
・data には、バックエンドから返ってきたユーザー情報などの JSON データが入っているはず!

if (response.ok) はレスポンスが200番台だったらって意味!つまりリクエストが成功したらってつかえる

const handleSubmit = async (e) => {
  e.preventDefault();
  if (!name || !password) {
    return;
  }
  try {
    const response = await fetch("http://localhost:8080/userApp/users/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, password }),
    });

    if (response.ok) {
      const data = await response.json(); // ここでレスポンスを取得
      console.log("ログイン成功:", data); // オブジェクトの中身を確認
      alert("ログイン成功!");

      window.location.href = "/home";
    } else {
      alert("ログインに失敗しました。");
    }
  } catch (error) {
    console.error("ログインエラー:", error);
  }
};
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?