Nuxt.js(Vuex)にてurlを動的に取得してapiにアクセスしたい
記事・投稿一覧からVuexにてURLをもとにして動的にデータを取得して
表示したいと考えております。
そこで、APIへのアクセス→表示はうまくいったのですが、
動的なルーティングを実装する際に手詰まってしまい、質問させていただく次第です。
どうぞよろしくお願いします。
[ API express ] const { CONNECTION_URL, OPTIONS, DATABASE, } = require("../../config/mongodb.config.js"); const MongoClient = require("mongodb").MongoClient; const router = require("express").Router(); router.get("/*", (req, res) => { MongoClient.connect(CONNECTION_URL, OPTIONS, (error, client) => { const db = client.db(DATABASE); db.collection("posts") .findOne({ url: req.url, }) .then((doc) => { res.json(doc); }) .catch((error) => { throw error; }) .then(() => { client.close(); }); }); }); module.exports = router;
[ vuexの実装 ] export const state = () => ({ posts: [], }); export const getters = { posts: (state) => state.posts, }; ========================エラーが出力されてしまいます。 export const actions = { async getPost({ commit }) { const res = await this.$axios.$get(`/api/v1/posts/${this.$route}`); →取得できない const res = await this.$axios.$get(`/api/v1/${this.$route.params.id}`); →Cannot read property 'params' of undefined const res = await this.$axios.$get( `/api/v1/posts/2017/07/advanced-nodejs.html` ); →表示・取得できる commit("setPost", res); }, }; ======================== export const mutations = { setPost(state, data) { state.posts = data; }, };
VuexにてAxiosを使用した際に
アクセスしたurlを動的に取得できる方法を知りたいと思っております。
ご回答をお待ちしておりますので、どうぞよろしくお願いいたします。
試したこと
export const actions = { async getPost({ commit }) { const res = await this.$axios.$get(`/api/v1/posts/${this.$route}`); →取得できない const res = await this.$axios.$get(`/api/v1/${this.$route.params.id}`); →Cannot read property 'params' of undefined const res = await this.$axios.$get( `/api/v1/posts/2017/07/advanced-nodejs.html` ); →表示・取得できる commit("setPost", res); }, };
補足情報(FW/ツールのバージョンなど)
・nuxt: 2.0.0,
・express: 4.16.4,
・@nuxtjs/axios: 5.3.6,
・mongodb: 3.5.8",
回答にあたって必要な情報がございましたら、ご連絡をいただけたら幸いです。
あなたの回答
tips
プレビュー