1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

APIのパースについて

Posted at

はじめに

APIにあまり触れていなかったので学習しました
この記事はリクエストボディをパースしてぇって方向けです

リクエストボディとは

以下のPOSTリクエストが送られてきたとします
これはリクエストボディです
APIはこれを受け取り、読み取って処理します。

{
  "article": {
    "title": "How to train your dragon",
    "description": "Ever wonder how?",
    "body": "You have to believe",
    "tagList": ["reactjs", "angularjs", "dragons"]
  }
}

パース(parse)とは

  • JSON形式(文字列)をJavaScriptのオブジェクトに変換すること
  • JSONとはデータのやり取りに使われる形式(キーと値のセット)

Next.js(App Router)の書き方

const body = await req.json

リクエスト (req) のボディからJSONデータを非同期的に読み込み、JavaScriptのオブジェクトとして返すためのコード

  • reqはNext.jsのオブジェクト
  • req.json()は非同期メソッドでawaitが必要
  • 戻り値はパースされたオブジェクト

具体例

    export async function POST(req:NextRequest) {
        const body = await req.json()
        // bodyの中はすでにオブジェクト
        console.log(body.article.title) //"How to train your dragon"
    }

型をつける場合

type ArticleRequest = {
    article: {
        title: string
        description: string
        body: string
        tagList: string[]
    }
}

const  {artilce}: ArticleRequest = await req.json()

他のパース方法

  • req.text()
    • テキスト形式で取得(csvなど)
  • req.formData()
    • フォーム送信時の multipart/form-dataを扱う

まとめ

リクエストボディのパースとは、受け取ったJSONをJavaScriptのオブジェクトとして扱えるようにすること
Next.js(App Router)ではawait req.json()を扱うのが基本

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?