Vue(axios) + expressでセッション管理

2021.07.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Introduction

先日、クライアント側をVue.js、サーバ側をExpress
sessionを使おうとしたら少々つまづいたので、使用に関するメモです。

Environment

  • Client framework : Vue.js 3.0.11
  • Http Client : axios 0.21.1
  • Node : v14.16.1
  • express-session : 1.17.2

Create Vue template

とりあえず動くものがほしかったので、ここ からgit cloneしてソースもってきました。

% git clone https://github.com/bezkoder/vue-3-typescript-example
% cd vue-3-typescript-example
% npm install
% npm run serve 

> vue-3-typescript-example@0.1.0 serve vue-3-typescript-example
> vue-cli-service serve

 INFO  Starting development server...

 App running at:
  - Local:   http://localhost:8081/
  - Network: http://192.168.11.2:8081/

  Note that the development build is not optimized.
  To create a production build, run npm run build.

Issues checking in progress...
No issues found.

npm installしてnpm runすれば8081ポートで起動します。
CRUD機能が試せるみたいですが、(自分の環境では)動きませんでした。
が、ひととおり設定はできてるのでこれでOK。  

このテンプレートではサーバとの通信にaxiosをつかっているのですが、
セッションを使うためにsrc/http-common.tsを修正します。

const apiClient: AxiosInstance = axios.create({
  baseURL: "<サーバサイドAPIのURL>",
  withCredentials: true,
  headers: {
    "Content-type": "application/json"
  },
});

withCredentials というパラメータをtrueに設定すればOKとのことです。

Create Express template

次はサーバサイドをExpressでつくります。
まずはexpress-generatorをインストール。

% npm install express-generator

expressコマンドでテンプレート作成します。

% express express-server
% cd express-server
% npm install

express-sessionをインストール。

% npm install express-session

app.jsでexpress-sessionを使い、セッションの設定をします。
ドキュメントはこのへんをみました。

//app.js
var session = require('express-session')

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  maxage: 1000 * 60 * 30
}))

あとはrequest.sessionで情報を取得したり、 request.session.hogeとか適当に値を設定したりします。

//routes/index.js

router.get('/api/hogehoge', function(req, res, next) {
  req.session
  res.json({'message': 'Hello World'})
});

このAPIをさきほどのVueクライアントから呼び出すようにすればOKです。