Cookie そのものについての説明は、別途記事を書いているのでそちらを参照。
動作確認に使った実行環境やツールのバージョンは以下の通り。
- Google Chrome 85.0.4183.121
- Deno 1.4.4
- curl 7.54.0
Deno
まずはサーバから Cookie をセットする方法。
標準モジュールが提供しているsetCookie
を使うと、レスポンスヘッダに簡単にset-cookie
フィールドを追加できる。
Cookie を取り出すためのgetCookies
も提供されている。
import { listenAndServe, ServerRequest, setCookie, getCookies, } from "https://deno.land/std@0.74.0/http/mod.ts"; const getRouting = async (req: ServerRequest) => { switch (req.url) { case "/cookie": { const response = { status: 200, headers: new Headers({ "content-type": "text/plain", }), body: "Set cookies.\n", }; setCookie(response, { name: "Space", value: "Cat" }); setCookie(response, { name: "my-cookie", value: "abc" }); req.respond(response); break; } default: req.respond({ status: 404, headers: new Headers({ "content-type": "text/plain", }), body: "Not found\n", }); break; } }; listenAndServe({ port: 8080 }, async (req: ServerRequest) => { console.log(req.headers.get('cookie')); console.log(getCookies(req)); switch (req.method) { case "GET": getRouting(req); break; default: req.respond({ status: 405, }); } });
サーバを起動してhttp://localhost:8080/cookie
にアクセスすると、Cookie が付与される。
初回アクセス時は Cookie が存在しないので、以下の結果になる。
console.log(req.headers.get('cookie')); // null console.log(getCookies(req)); // {}
2 回目以降はリクエストヘッダにCookie: Space=Cat; my-cookie=abc
が含まれているので、以下の結果になる。
console.log(req.headers.get('cookie')); // Space=Cat; my-cookie=abc console.log(getCookies(req)); // { Space: "Cat", "my-cookie": "abc" }
curl
curl で Cookie を送信するには、-b
オプションを使う。
以下を実行すると、リクエストヘッダにcookie: name=value; a=b
が含まれる。
$ curl -b "name=value; a=b" http://localhost:8080/
-c
オプションを使うと、サーバから送られてきた Cookie の内容をファイルに保存できる。
$ curl -c cookie.txt http://localhost:8080/cookie
上記のコマンドを実行すると、以下の内容のcookie.txt
が作られる。
# Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. localhost FALSE / FALSE 0 Space Cat localhost FALSE / FALSE 0 my-cookie abc
先程紹介した-b
オプションには、この形式のファイルを渡すこともできる。
以下のコマンドを実行すると、リクエストヘッダにcookie: Space=Cat; my-cookie=abc
が含まれる。
$ curl -b cookie.txt http://localhost:8080/cookie