HTTPリクエスの確認方法 3 つ

前回は、 npm start した結果をブラウザで確認しました。ブラウザ以外での確認方法をまとめておく。

REPL で送信結果確認

書籍「ハンズオン Node.js」では、 isomorphic-fetch を使う方法が紹介されています。

isomorphic-fetch

Fetch for node and Browserify. Built on top of GitHub's WHATWG Fetch polyfill.

ブラウザ環境と Node.js 環境の差異およびブラウザ間の差異もポリフィルされる。

書籍のからの受け売り。もしかすると既に書いたかも? *REPL** で await を使う。

--experimental-repl-await のドキュメント

$ npm i isomorphic-fetch@3.0.0
$ node --experimental-repl-await
> require('isomorphic-fetch')
> console.log(_.status, await _.json())
200 [
  { id: 1, title: 'ネーム', completed: false },
  { id: 2, title: '下書き', completed: false }
]

curl

curl コマンドで確認しておきます。

$ curl -v http://localhost:3000/api/todos
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /api/todos HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 95
< ETag: W/"5f-UYFVhnuO01ilODP6V2hybnHL7sU"
< Date: Sun, 27 Dec 2020 01:48:07 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
* Connection #0 to host localhost left intact
[{"id":1,"title":"ネーム","completed":false},{"id":2,"title":"下書き","completed":false}]

VSCode で確認

REST Client for Visual Studio Code を使って同様に確認。

拡張子は http または rest 。demo.rest` ファイルを作成し、以下を記述。

GET http://localhost:3000/api/todos  HTTP/1.1

Send Request の文字をクリックする。

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 95
ETag: W/"5f-UYFVhnuO01ilODP6V2hybnHL7sU"
Date: Sun, 27 Dec 2020 02:19:55 GMT
Connection: close

[
  {
    "id": 1,
    "title": "ネーム",
    "completed": false
  },
  {
    "id": 2,
    "title": "下書き",
    "completed": false
  }
]

curl に比べレスポンスが読みやすいかな?でも私くらい初心者になると URL をクォートしちゃうんですよね。

存在しないURLでの動作確認

存在しない URL に対しフェッチする。

> await fetch('http://localhost:3000/api/foo')
> Response {
> ...
> [Symbol(Response internals)]: {

    url: 'http://localhost:3000/api/foo',
    status: 404,

...

> console.log(_.status, await _.text())
> 404 <!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/foo</pre>
</body>
</html>

期待通りに 404 が返された。レスポンスは JSON 形式で返されない。書籍「ハンズオン Node.js」では response.text() とし、テキスト形式で取得している。