LoginSignup
25
23

More than 5 years have passed since last update.

Nuxt.jsでサーバーサイドからAPIアクセスして表示を行う

Posted at

はじめに

過去にVue.js + axiosで作成したAPIアクセス確認ソースをNuxt.js上に移植してみる。
ついでにNuxt.jsのSSR(サーバーサイドレンダリング)も試してみる。

環境

Windows10 Pro
Docker for Windows
Nuxt.js 1.4.2

下準備

Hot Reloadingの設定

Windows + Docker環境だとHot Reloading(ソース変更時に自動ビルドしてくれる機能)が上手く動かないので、webpackの設定でポーリングによるチェックを行うようにしておく。

next.config.js
watchers: {
  webpack: {
    aggregateTimeout:300,
    poll: 1000
  }
}

参考ページ: https://github.com/nuxt/nuxt.js/issues/2481

axiosのインストール

APIへアクセスするためにaxiosを使用したいのでインストールする。

$ yarn add @nuxtjs/axios

移植したソース内容

pages/search/index.vue
<template>
    <div id="app">
        <h1>Nuxt API Test</h1>
        <div class="itemContainer">
            <Item
              v-for="(result, index) in items" :key="index"
              v-bind:id="result.id"
              v-bind:name="result.name"
              v-bind:value="result.value"
            >
            </Item>
        </div>
    </div>
</template>

<script>
    import Item from '~/components/Item.vue'
    import axios from 'axios'

    export default {
        components: { Item },
        head: { title: 'Nuxt API Test' },
        asyncData ({ params }) {
            return axios
                .get("https://script.googleusercontent.com/macros/echo?…以下略…")
                .then((response) => {
                    return { items: response.data }
                })
        }
    }
</script>

<style scoped>
.itemContainer{
    display: flex;
}
</style>
components/Item.vue
<template>
    <div class="item">
        <div>ID: {{id}}</div>
        <div>名前: {{name}}</div>
        <div>値: {{value}}</div>
    </div>
</template>

<script>
    export default {
        name: "Item",
        props: {
            id: Number,
            name: String,
            value: Number
        }
    }
</script>

<style scoped>
.item {
    border: solid;
    margin: 5px;
}
</style>

実行結果

http://localhost:3000 にアクセス

2018-08-26_17h00_15.png

SSR(サーバーサイドレンダリング)での通信

Nuxt.jsでは asyncData() によりサーバーサイドでAPI通信によるデータ取得をしてレンダリングをすることが出来ます。

そのため、CORS対応されていないサイトからデータを取得する場合に、過去記事 で書いたようにプロキシ的なAPIを間に挟まなくてもSSRにより表示を行うことが出来るようです。

クライアントサイドからAjaxによる取得をすることも可能なので、この辺は要件によってクライアント/サーバーどちらから通信をした方が良いのかを選択する必要がありそうです。

25
23
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
25
23