Next.jsではクライアント側から呼び出せるAPIを簡単に構築することができます。
目次
ルーティング
pages/apiディレクトリ配下にファイルを配置することでクライアント側からAPIを呼び出せるようになります。
以下のような配置なら、ホスト/api/testでtest.tsの実装したAPIがにルーティングして、/test_pageでtest_page.tsで実装したページにルーティングします。
src
|
|- pages
|- api
| |- test.ts
|- test_page.ts
実装
以下のようにNextApiRequestとNextApiResponseを引数にした関数をexport defaultしてあげることでAPIが構築できます。
GET/POSTで特に差分はなさそうです。req.methodに全部大文字のhttpメソッド名が入ります。
import { NextApiRequest, NextApiResponse } from 'next'
type TestRes = {
title: string
content: string
}
const handler (req: NextApiRequest, res: NextApiResponse<TestRes>) => {
const result: TestRes = {
title: 'test title',
content: 'test content',
}
res.status(200).send(result)
}
export default handler
各種パラメータ – query, headers, cookies, body
以下の例のように、クエリパラメータならreq.query.<パラメータ名>、cookieならreq.cookies.<cookie名>、ヘッダーはreq.headers.<ヘッダー名>、bodyはreq.body[“フィールド名”]で取得できます。
import { NextApiRequest, NextApiResponse } from 'next'
type TestRes = {
title: string
content: string
}
const handler = (req: NextApiRequest, res: NextApiResponse<TestRes>) => {
const result: TestRes = {
title: `id: ${req.query.id}, authorization header: ${req.headers.authorization}`,
content: `body[test]: ${req.body['test']}, cookie[test]: ${req.cookies.test}`,
}
res.status(200).send(result)
}
export default handler
上記のサンプル実装でnpm run devなどしてデプロイしている状態で、このようなリクエストをcurlで投げると以下のような取得結果が取得できると思います。
curl -X POST -H "Authorization: test_auth_header" -H "Cookie:test=testcookie" -H "Content-Type: application/json" -d "{\"test\":\"test body\"}" http://localhost:3000/api/demo/test?id=testid
# 取得結果
{"title":"id: testid, authorization header: test_auth_header","content":"body[test]: test body, cookie[test]: testcookie"}