Memo

メモ > 技術 > フレームワーク: Next.js > APIアクセス

APIアクセス
src/app/request-api/route.ts
'use server'; export async function GET(request: Request) { const res = { content: 'Hello, World!' }; return new Response(JSON.stringify(res), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } export async function POST(request: Request) { const data = await request.json(); return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }
src/app/request/page.tsx
'use client' import { useState, useEffect } from 'react' export default function Request() { const [data, setData] = useState('') const [input, setInput] = useState('') useEffect(() => { fetchData() }, []) const fetchData = async () => { try { const response = await fetch('http://localhost:3000/request-api', { method: 'GET' }) if (!response.ok) { throw new Error('Network response was not ok.') } const json = await response.json() setData(json) } catch (error) { console.error('Failed to fetch data: ', error) } } const doSubmit = async (event) => { event.preventDefault() try { const response = await fetch('http://localhost:3000/request-api', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ content: input }), }) if (!response.ok) { throw new Error('Network response was not ok.') } const json = await response.json() setData(json) } catch (error) { console.error('Failed to post data: ', error) } } return ( <main> <h1 className="title">Request</h1> <form className="m-5" onSubmit={doSubmit}> <input type="text" value={input} className="input" onChange={(e) => setInput(e.target.value)} /> <button className="button" type="submit">送信</button> </form> <div className="message"> {data ? ( <pre>{JSON.stringify(data, null, 2)}</pre> ) : ( <p>Now Loading...</p> )} </div> </main> ) }

Advertisement