POST リクエストの処理
POSTリクエストの処理を行う。
"use strict"; const express = require("express"); const app = express(); let todos = [ { id: 1, title: "ネーム", completed: true }, { id: 2, title: "下書き", completed: false }, { id: 3, title: "フルーツグラノーラ購入", completed: false }, { id: 4, title: "ブログタグ見直し", completed: true }, ]; app.use(express.json()); app.get("/api/todos", (req, res) => { if (!req.query.completed) { return res.json(todos); } const completed = req.query.completed === "true"; res.json(todos.filter((todo) => todo.completed === completed)); }); let id = todos.length; app.post("/api/todos", (req, res, next) => { const { title } = req.body; if (typeof title !== "string" || !title) { const err = new Error("title is required"); err.statusCode = 400; return next(err); } const todo = { id: (id += 1), title, completed: false }; todos.push(todo); res.status(201).json(todo); }); app.use((err, req, res, next) => { console.error(err); res.status(err.statusCode || 500).json({ error: err.message }); }); app.listen(3000);
app.post("/api/todos", (req, res, next) => {
この部分が今回の肝です。引数 next
は次の処理につなぐ、渡すときに用いるようだ。 return next(err);
と書かれている。エラー発生時は、 Express の標準エラー処理に渡しているとの意味と理解した。
API リファレンス
今回使用した Exrepss.js の API リファレンス
Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Routes HTTP GET requests to the specified path with the specified callback functions.
Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide.
Routes HTTP GET requests to the specified path with the specified callback functions.
動作確認
$ node --experimental-repl-await > require('isomorphic-fetch') await fetch('http://localhost:3000/api/todos', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: 'ペン入れ' }), }); ... > console.log(_.status, await _.json()) 201 { id: 5, title: 'ペン入れ', completed: false }
VSCodeでも確認...
[VSCode] REST Client は変数を使うと API の環境やパラメータ変更が楽になる!
リクエストボディは、1 行空けて書きます。
Header name must be a valid HTTP token ["{"]
これがわからなかった。
午後のティータイムに飲むはずだった淹れたての熱々のコーヒが、アイスコーヒーに変化した!
POST http://localhost:3000/api/todos HTTP/1.1 content-type: application/json { "title": "コーヒーを淹れる" }
リクエストを投げる。
HTTP/1.1 201 Created X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 61 ETag: W/"3d-lsYXjM2PnXTzrk+cbJdGSiPwFug" Date: Mon, 28 Dec 2020 05:06:14 GMT Connection: close { "id": 5, "title": "コーヒーを淹れる", "completed": false }