LoginSignup
1
0

More than 1 year has passed since last update.

Freshの備忘録 Part1 ~ GETとPOSTメソッドの使い方 ~

Posted at

基本的な内容ですが、Freshを学んでいるときに地味に時間を要してしまったので、残しておきます。

内容

GETとPOSTでのデータの受け渡し方法について

■GETでのデータ受け渡し

データ送信用のページ

routes/get-send.tsx
import { Handlers, PageProps } from "$fresh/server.ts";

export default function GetSendPage() {
  return (
    <div>
      <form method="GET" action="/get-reception">
        <input type="text" name="userName" />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

データ受信用のページ

routes/post-reception.tsx
import { Handlers, PageProps } from "$fresh/server.ts";

interface Data {
  userName: string;
}

export const handler: Handlers<Data> = {
  async GET(req, ctx) {
    const url = new URL(req.url);
    const userName = url.searchParams.get("userName") || "";
    return ctx.render({ userName });
  },
};

export default function PostReceptionPage({ data }: PageProps<Data | null>) {
  if (!data?.userName) {
    return <h1>そんなユーザーはいないでござる</h1>;
  }

  return (
    <div>
      <h1>{data.userName} です </h1>
    </div>
  );
}

■POSTでのデータ受け渡し

データ送信用のページ

routes/post-send.tsx
import { Handlers, PageProps } from "$fresh/server.ts";

export default function PostSendPage() {
  return (
    <div>
      <form method="POST" action="/post-reception">
        <input type="text" name="userName" />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

データ受信用のページ

routes/post-reception.tsx
import { Handlers, PageProps } from "$fresh/server.ts";

interface Data {
  userName: string;
}

export const handler: Handlers<Data> = {
  async POST(req, ctx) {
    const formData = await req.formData();
    const userName = formData.get("userName")?.toString() || "";
    return ctx.render({ userName });
  },
};

export default function PostReceptionPage({ data }: PageProps<Data | null>) {
  if (!data?.userName) {
    return <h1>そんなユーザーはいないでござる</h1>;
  }

  return (
    <div>
      <h1>{data.userName} です </h1>
    </div>
  );
}

参考資料

1
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
1
0