LoginSignup
0
1

More than 5 years have passed since last update.

Cookieを取得してブラウザ上に最後にアクセスした時間を表示する

Last updated at Posted at 2018-08-08

Cookieとは?

  • Webブラウザに情報を記録するための仕組み
  • 有効期限を指定できる

内部的にはHTTPのリクエストヘッダのCookieという項目と、レスポンスヘッダのSet-Cookieという項目を利用することで実現

Cookieを取得してブラウザ上に最後にアクセスした時間を表示する

index.js

'use strict';
const http = require('http');
const server = http.createServer((req,res) => {
  const now = new Date().getTime();
  res.setHeader('Set-Cookie', 'last_access=' + now + ';');
  const last_access_time = req.headers.cookie ? parseInt(req.headers.cookie.split('last_access=')[1]): now;
  res.end(new Date(last_access_time).toString());
});
const port = 8000;
server.listen(port, () => {
  console.info('Listening on' + port);
});

解説

const now = new  Date();
res.setHeader('Set-Cookie', 'last_access=' + now + ';');

nowという変数に現在時間のミリ秒の数値を代入して、Cookieとしてlast_accessというキー名でヘッダにセットしている。
req.headers.cookie.splitでブラウザから送られてきたCookieの内容を参照できる。

const last_access_time = req.header.scookie.split('last_access')[1]): now;
Cookieが取得できたらlast_access=〇〇からミリ秒を表す文字列〇〇を抜き出し、parseInt()で数値に変換してlast_access_time
に代入している。
もし、Cookieが取得できなかったらnowlast_access_timeに代入する。

res.end(new Date(last_access_time).toString());
そして取得した最終アクセス時間のミリ秒表記をnew Dateに渡し、文字列に変換している。

所感

セッションが残って面倒な場面でCookieを削除することはよくあるが、仕組みを知るとブラウザに情報を保存できるCookieのありがたみを実感する。

0
1
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
0
1