From e8b4a30f1d0f27644c9b12f0c8785f7aba567e38 Mon Sep 17 00:00:00 2001 From: Tiger Ren Date: Thu, 23 Jan 2025 00:22:16 +0800 Subject: [PATCH] Implement API call functionality in Home component with button to fetch and display message --- src/app/api/hello/route.ts | 10 ++++++++++ src/app/page.tsx | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/app/api/hello/route.ts diff --git a/src/app/api/hello/route.ts b/src/app/api/hello/route.ts new file mode 100644 index 0000000..c1fcc3f --- /dev/null +++ b/src/app/api/hello/route.ts @@ -0,0 +1,10 @@ +import { NextResponse } from 'next/server'; + +export async function GET() { + return NextResponse.json({ message: 'Hello from API' }); +} + +export async function POST(request: Request) { + const body = await request.json(); + return NextResponse.json({ received: body }); +} \ No newline at end of file diff --git a/src/app/page.tsx b/src/app/page.tsx index 3eee014..894ad35 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,6 +1,16 @@ +'use client'; +import { useState } from 'react'; import Image from "next/image"; export default function Home() { + const [apiMessage, setApiMessage] = useState(''); + + const handleApiCall = async () => { + const response = await fetch('/api/hello'); + const data = await response.json(); + setApiMessage(data.message); + }; + return (
@@ -23,6 +33,20 @@ export default function Home() {
  • Save and see your changes instantly.
  • +
    + + {apiMessage && ( +

    + {apiMessage} +

    + )} +
    +