Implement API call functionality in Home component with button to fetch and display message

This commit is contained in:
Tiger Ren 2025-01-23 00:22:16 +08:00
parent 242e941472
commit e8b4a30f1d
2 changed files with 34 additions and 0 deletions

View File

@ -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 });
}

View File

@ -1,6 +1,16 @@
'use client';
import { useState } from 'react';
import Image from "next/image"; import Image from "next/image";
export default function Home() { export default function Home() {
const [apiMessage, setApiMessage] = useState<string>('');
const handleApiCall = async () => {
const response = await fetch('/api/hello');
const data = await response.json();
setApiMessage(data.message);
};
return ( return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start"> <main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
@ -23,6 +33,20 @@ export default function Home() {
<li>Save and see your changes instantly.</li> <li>Save and see your changes instantly.</li>
</ol> </ol>
<div className="flex flex-col items-center gap-4">
<button
onClick={handleApiCall}
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
>
Test API
</button>
{apiMessage && (
<p className="text-sm font-mono bg-black/[.05] dark:bg-white/[.06] px-3 py-2 rounded">
{apiMessage}
</p>
)}
</div>
<div className="flex gap-4 items-center flex-col sm:flex-row"> <div className="flex gap-4 items-center flex-col sm:flex-row">
<a <a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5" className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"