app/route.ts
app/内に配置する
例えば、app/features/hoge/route.tsに配置すると、
fetch('/feasure/hoge', {..})でアクセスできる
app/features/hogeというpathを見た時に、
app/features/hoge/page.tsxというページのことを指してるのか
app/feasutrs/hoge/route.tsというAPIのことを指してるのか判断できないため
HTTP Methodsをそのまま関数名にする感じで定義する
code:app/feasutrs/hoge/route.ts
import { NextRequest, NextResponse } from "next/server";
export function GET(req: NextRequest) {
return NextResponse.json({ message: "hello" })
}
関数名はmethod名
GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
引数
code:ts
return new NextResponse("error!", {
status: 500,
headers: { "Content-Type": "text/plain" },
});
code:ts
return NextResponse.json({ message: "hello,world!" })
GETを使った時はデフォルトでcacheされるという感じかな
cacheを回避(オプトアウト)する方法もいくつか書いている
Using the Request object with the GET method.
GET以外のmethodを使用した場合
Headerを読む
code:route.ts
import { type NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const requestHeaders = new Headers(request.headers)
}
code:ts
import { type NextRequest } from 'next/server'
export function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams
const query = searchParams.get('query')
// query is "hello" for /api/search?query=hello
}
POSTの例
code:app/features/hoge/route.tsx
export async function POST(req: NextRequest) {
const { image } = await req.json(); // bodyを取得
await save(image);
return NextResponse.json({ message: "success" });
}
code:呼ぶ側.ts
const result = await fetch("/features/hoge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image }),
});
req.formData()もある
redirectする
code:route.ts
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
}
Streamingする