Reputation: 23
I've been introducing myself to Vue/Nuxt and have begun experimenting with API's. I'm trying to move the logic in my NuxtServerInit function to an API.
nuxtServerInit(vuexContext, context) {
return context.app.$axios
.$get(process.env.baseUrl + "/posts.json")
.then(data => {
const postsArray = [];
for (const key in data) {
postsArray.push({ ...data[key], id: key });
}
vuexContext.commit("modules/modPost/setPosts", postsArray);
})
.catch(e => context.error(e));
}
The problem I'm having is accessing the context in order to make the DB call.
The API looking something like this:
const { Router } = require("express");
const glob = require("glob");
const router = Router();
router.post("/carousel/posts", async function(req, res) {
return context.app.axios
.get(process.env.baseUrl + "/posts.json")
.then(data => {
const postsArray = [];
for (const key in data) {
postsArray.push({ ...data[key], id: key });
}
vuexContext.commit("modules/modPost/setPosts", postsArray);
})
.catch(e => context.error(e));
});
module.exports = router;
I tried making a POST request thinking I could send the context as a parameter but I it feels wrong...
async asyncData({ $axios }) {
const ps = await $axios.$post(
"http://localhost:3000/api/carousel/posts", {context});
return { ps };
}
I should note here, that I am fairly sure that in the API, the line is wrong:
vuexContext.commit("modules/modPost/setPosts", postsArray);
I believe it would generally execute in the asyncdata, on what is returned by the API.
So to summarize, I have two questions.
Thanks!
Upvotes: 0
Views: 1510
Reputation: 23
I can't believe I figured it out within ten minutes of posting. Ugh.
For number 2, added this to the API:
router.post("/carousel/posts", async function(req, res) {
const darts = await axios.get(process.env.baseUrl + "/posts.json");
return res.json(darts.data);
});
And asyncData:
async asyncData({ $axios, store }) {
//console.log($axios);
const ps = await $axios.$post(
"http://localhost:3000/api/carousel/posts"
);
const postsArray = [];
for (const key in ps) {
postsArray.push({ ...ps[key], id: key });
}
store.commit("modules/modPost/setPosts", postsArray);
return { ps };
}
Also still interested in reasonability / best practices / opinions...
Upvotes: 0
Reputation: 1240
First of all, I see here bad workflow. I suggest you to analyze how the communication between the Express and Nuxt is going. Take a look at this auth example
vuexContext.commit is the vuex method, and you use it on the server side (express), which is a mistake. In simplified terms, communication could look like:
Upvotes: 1