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?

Next.jsを使って簡単にAPIを作ってみる

Posted at

はじめに

Next.jsを使えば簡単にAPIが作れるらしいので作ってみる。

対象者はPCでnpm, npxコマンドが使える人。

Node.jsをインストールしていない人はインストールをお願いします。

実際にやってみる

まずはNext.jsプロジェクトを作成します。

npx create-next-app@latest
npm run dev

http://localhost:3000/にアクセス。

次にapp/api/というディレクトリを作成し、apiフォルダの中にroute.tsを作成します。

image.png

route.tsに以下のように書くとGETリクエストに対してJSONデータを返してくれます。

route.ts
import { NextResponse } from "next/server";

export async function GET() {
    return NextResponse.json({
        message: "データを取得",
        hoge: "hello, world",
    });
}

localhost:3000/apiにアクセスすると先ほど書いたjsonが表示されます。

image.png

次はフロントエンドからデータを取得してみます。

app/page.tsxを以下のように書き換えてください。

fetch関数で/apiにGETリクエストを送り、受け取ったデータをコンソールに表示しています。

buttonを押したときにgetDataが呼び出されるのでlocalhostにアクセスしてbuttonをクリックするとブラウザのコンソールに出力されると思います。

page.tsx
"use client";

export default function Home() {

  const getData = async () => {
    const response = await fetch("/api");
    const data = await response.json();
    console.log(data);
  }

  return (
    <>
      <button onClick={getData}>button</button>
    </>
  );
}

F12、Ctrl+Shift+Iなどでコンソールを開いてください。

image.png

次はWebページ上に表示してみましょう。

app/page.tsx
"use client";

import { useState } from "react";

export default function Home() {
  const [data, setData] = useState();

  const getData = async () => {
    const response = await fetch("/api");
    setData(await response.json());
  }

  return (
    <div className="text-center">
      <button onClick={getData}>button</button>
      {data && <div>{data && data.hoge}</div>}
    </div>
  );
}

buttonをクリックすると、dataに中身が入るのでdata.hogeがブラウザ上に表示される。

image.png

もちろんroute.tsのhoge: "hello, world"を編集すれば返す値を変えられる。

参考

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?