1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsで認証認可入り掲示板APIのフロントエンド部分を構築する #3 個別記事ページの作成

Last updated at Posted at 2020-09-25

Nuxt.jsで認証認可入り掲示板APIのフロントエンド部分を構築する #2 NuxtとRailsとの疎通テスト

個別記事ページの作成

$ mkdir pages/posts
$ touch pages/posts/_id.vue
pages/posts/_id.vue
<template>
  <v-layout
    column
    justify-center
    align-center
  >
    <v-flex
      xs12
      sm8
      md6
    >
      <v-card>
        <v-card-title class="headline">
          {{ post.subject }} - {{ post.user.name }}
        </v-card-title>
        <v-card-text>
          {{ post.body }}
        </v-card-text>
      </v-card>
    </v-flex>
  </v-layout>
</template>

<script>
export default {
  validate ({ params }) {
    return /^\d+$/.test(params.id)
  },
  async asyncData ({ $axios, params }) {
    const response = await $axios.$get(`/v1/posts/${params.id}`)
    return {
      post: response.post
    }
  }
}
</script>

Nuxtでは上記のようにpages/hoge/_id.vueとすることで、hoge/{id}のような動的ページが作られます。

バリデートは数値型のみ許容するように設定しています。以下、公式ドキュメント参照。
ルーティング - NuxtJS

そしてasyncDataというSSR用のメソッドでv1/posts/${params.id}とすることで、URLのid部分の数値から固定のpostを取得しているわけです。

なお、今回はpostの値をVuexのstoreに保存していません。
storeはなんでもかんでも保存を保存しておく場所ではなく、他のmoduleやサイト全体で使う必要があるか考え、そうでなければ不用意に突っ込まないほうがいいです。

もしブラウザで以下の通り表示されたら、とりあえずOKです。

show.png

indexから個別ページにリンクを設置

indexから個別ページにリンクを貼ります。

pages/index.vue
       <v-card v-for="post in posts" :key="post.id">
         <v-card-title class="headline">
-          {{ post.subject }} - {{ post.user.name }}
+          <n-link :to="`/posts/${post.id}`">
+            {{ post.subject }} - {{ post.user.name }}
+          </n-link>
         </v-card-title>
         <v-card-text>

list.png

リンクになっていますね。

CORS対策

ではindexから個別ページに飛んでみましょう。

error.png

エラーになりましたか?
実はこれがエラーメッセージ読んでも原因が特定しづらく結構厄介なものです。
以前この問題の対応策を書き残していますので、詳細を知りたい方は以下の記事を。
Nuxt.jsでURL直叩きの時はページが表示されるのに、nuxt-linkやブラウザバックでAn error occurredになる

さて上記記事にも書きましたが、原因はページ遷移した場合はSSR(サーバサイドレンダリング)ではなくCSR(クライアントサイドレンダリング)になるため、CORS(オリジン間リソース共有)の対策が必要です。

nuxt.config.js
   ** Nuxt.js modules
   */
   modules: [
-    '@nuxtjs/axios'
+    '@nuxtjs/axios',
+    '@nuxtjs/proxy'
   ],
-  axios: {},
+  axios: {
+    proxy: true
+  },
+  proxy: {
+    '/v1/': {
+      target: 'https:/xxxxxxxxxxx.ap-northeast-1.amazonaws.com:8080/'
+    }
+  },

targetはご自身のRails APIエンドポイントに置き換えてください。

この設定が済めば、indexも個別ページも、ブラウザバックやn-link(nuxt-link)による遷移時も正常に表示されるはずです。

続き

Nuxt.jsで認証認可入り掲示板APIのフロントエンド部分を構築する #4 サインアップページの作成
連載目次へ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?