nuxt-communityのexpress-templateを試してみる #nuxtjs #vuejs

概要

vue-cliから作れるNuxt.jsのテンプレートに、express-templateというのがある。

Nuxt.jsと同時にExpressを起動させて、バックエンドとして動かすことが可能。

Nuxt.js内でバックエンドのMockを作って動かせるので、フロントエンドとバックエンドの開発が切り分けるのが容易になる。

github.com

プロジェクト作成

vue-cliでプロジェクトを作成する。

$ vue init nuxt-community/express-template nuxt-express-sample
$ cd nuxt-express-sample
$ npm install # or yarn install

バックエンドのMockAPIを作成

下記のようなjsonを返すAPIを作成する。

[
  { name: 'とろ', price: 300 },
  { name: 'いか', price: 200 },
  { name: 'かっぱ巻き', price: 100 }
]

Routerの作成

server/api/sushi.js 名前でRouterを作成する。

import { Router } from 'express'

const router = Router()

// ダミーのレスポンスを定義
const sushi = [
  { name: 'とろ', price: 300 },
  { name: 'いか', price: 200 },
  { name: 'かっぱ巻き', price: 100 }
]

// `/api/sushi` のパスでアクセスできるようにする
router.get('/sushi', function(req, res, next) {
  // json形式で返却
  res.json(sushi)
})

export default router

Routerの登録

作成したRouterを server/api/index.js で登録する。

import { Router } from 'express'
// 作成したRouterのimport
import sushi from './sushi'

const router = Router()

// 作成したRouterの登録
router.use(sushi)

export default router

起動

起動して、アクセスしてみる。

http://localhost:3000/api/sushi

$ yarn dev

フロントエンドの作成

APIで取得したJSONを、フロントで一覧として表示してみる。

pages/sushi/index.vue を作成する。

<template>
<div id="sushi-list">
  <ul>
    <li v-for="(item) in sushiList" v-bind:key="item.name">
      {{item.name}}: {{item.price}}円</li>
  </ul>
</div>
</template>

<script>
// APIを叩くときにはaxiosが必要
import axios from '~/plugins/axios'

export default {
  data: function() {
    return {
      sushiList: []
    }
  },
  // asyncDataでレンダリング前にAPIを呼ぶ
  asyncData(context) {
    return axios.get('/api/sushi').then(res => {
      // asyncDataでreturnしたものはdataにマージされる
      return { sushiList: res.data }
    })
  }
}
</script>

起動

起動して、アクセスしてみる。

起動コマンドは変わらない(NuxtもExpressも一緒に立ち上がる)。

http://localhost:3000/sushi

$ yarn dev

asyncDataで取得したデータが表示される。

asyncDataだとSSR(サーバサイドレンダリング)するので、curlとかで取得してもAPIのレスポンスが反映されている。

またExpressも同時に起動しているので、APIにアクセスしても同様に確認できる。

まとめ

少なくとも開発時において、プロジェクト単体で簡単に動作できるというのは素敵。