Need some help in solving a reload problem.
I fetch data via service:
import axios from 'axios'
const apiClient = axios.create({
baseURL: 'www.domain/api/v1',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
and
export default {
getCompanies() {
return apiClient.get('/companies')
},
in store:
export const actions = {
fetchCompanies({ commit }) {
return CompanyService.getCompanies().then(response => {
commit('SET_COMPANIES', response.data)
})
},
in pages/companies:
async fetch({ store, error }) {
try {
await store.dispatch('company/fetchCompanies')
} catch (e) {
error({
statusCode: 503,
message: 'Unable to fetch Companies at this time'
})
}
},
works fine, but no data on page reload.
Some help would be great.
If you are using it on a pagination component the reason it is not reloading is that fetch it will be called server-side once and in the client-side just when navigating to further routes.
The fetch method is not called on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can setup parameters that should be listened to through the watchQuery property of your page component. Learn more on the API watchQuery page.
Looks Nuxt documentation: https://nuxtjs.org/api/pages-fetch/
You can use watchQuery to fix this.
https://nuxtjs.org/api/pages-watchquery
Related
i've a vue app which requires a token when sending a request each time i try to send a request i keep getting token not defined... here's the error
this how i call my methods property in script tag
<script>
import { mapActions } from "vuex";
import axios from "axios";
export default {
name: "Products",
data() {
return {
addresses: [],
products: []
};
},
methods: {
onDeleteAddress(id, index) {
axios
.delete(`http://localhost:5000/api/addresses/${this.$route.params.id}`,
{
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
}
}
)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
this my vue template
Delete
this works in my mounted life cycle hook but when i input it in my methods component i get an error
const token = localStorage.getItem("token");
please how can i get the token stored in my local storage and define it in my vue methods conponent
In first make sure the item is already stored in the localstorage
Second instead of calling it from the localstorage it is better to define it in main.js file as global variable so you can use it free every where
Example
Vue.prototype.$globalData = Vue.observable({ token: localStorage.getItem("token") });
And now you can use it in your methods like this
this.$globalData.token
You can as much as you want variable in the globalData object
I have a locally hosted mongodb database with mongoose, express, axios, and a Vue front end. Right now I'm trying to access a single object from an exported array, but I'm missing the mark and getting "undefined" as the result.
vue.config.js:
module.exports = {
devServer: {
proxy: 'http://localhost:3000',
}
}
here's the front end Vue script meant to use the objects:
import axios from 'axios';
export default {
name: 'Game',
data () {
return {
pages: [],
currentPage: {},
pageTitle: "",
pageText: "",
options: [],
}
},
created () {
this.getPages();
},
methods: {
async getPages() {
try {
let res = await axios.get('/api/pages');
this.pages = res.data;
console.log(this.pages);
this.currentPage = this.pages[0];
console.log(this.currentPage);
return true;
} catch (error) {
console.log(error);
}
},
my "get" endpoint in pages.js:
router.get('/', async (req, res) => {
try {
let pages = await Page.find();
res.send({pages: pages}); //send result of search for pages as list of pages called "pages"
} catch (error) {
console.log(error);
res.sendStatus(500); //500 = server could not fulfill request
}
});
the route in server.js:
const pages = require('./routes/pages');
app.use('/api/pages', pages);
app.listen(3000, () => console.log('Server listening on port 3000!'));
module.exports = app;
and here's the console output, with the "pages" object from vue's data property and the "currentPage" that's supposed to be at pages[0] (printed to console in earlier example):
I can access the api at 'localhost:3000/api/pages' just fine, but how do I break into that array and access the first page object? I want to get an object from the list axios fetches from mongoose, then hold that object in a variable so I can access it's properties. The whole "pages > [[Target]] > pages > [ ]" is part of the problem I'm sure, but I don't know what to tell the code to open it.
Whoops! I realized my mistake. In pages.js I should have sent "res.send(pages);" After a whole couple days too XD
Hello im trying to add {{this.$route.params}} to my axios url for get the data on dedicated profil pages.
here is the part i want to add in axios url the "id" :
The Axios code from 'RikLamers' who explain me how to get data, it is where i want to add "this.$route.params" :
data() {
return {
results: [],
}
},
async mounted() {
await axios.get(`API url" ${to.params.id}`)
.then(response => {this.results = response.data.content})
},
but i mistake somewhere, hope someone can explain me ?
You can access URL param using this.$route.params.id. Use try catch, when you use await.
data() {
return {
results: [],
}
},
async mounted() {
try {
const response = await axios.get(`[Your API URL]/${this.$route.params.id}`)
this.results = response.data.content
catch (e) {}
},
I'm new to Vue.js Nuxt and all front-end stuff.
I have a question about API calls. I'm not sure what is the right way, the best practice here.
I have a store. In that store, I have actions that are calling my API and sets state eg.
async fetchArticle({ state, commit }, uuid) {
const response = await this.$axios.get(`articles/${uuid}/`)
commit('SET_ARTICLE', response.data)
},
And that is fine it is working for one component.
But what if I want to just fetch the article and not changing the state.
To be DRY first thing that comes to my mind is to create the service layer that is fetching the data and is used where it is needed.
Is it the right approach? Where can I find some real-world examples that I can take inspiration from?
Using the repository pattern to abstract your API is definitely a good idea! Whether you use the #nuxtjs/axios module or the #nuxt/http module, you can pass either instance to your repository class/function. Below a real world example of an abstracted "repository.js" file.
export default $axios => resource => ({
index() {
return $axios.$get(`/${resource}`)
},
create(payload) {
return $axios.$post(`/${resource}`, payload)
},
show(id) {
return $axios.$get(`/${resource}/${id}`)
},
update(payload, id) {
return $axios.$put(`/${resource}/${id}`, payload)
},
delete(id) {
return $axios.$delete(`/${resource}/${id}`)
}
})
You can then create a plugin to initialize all different kinds of repositories for your endpoints:
import createRepository from '~/path/to/repository.js'
export default (ctx, inject) => {
const repositoryWithAxios = createRepository(ctx.$axios)
const repositories = {
posts: repositoryWithAxios('posts'),
users: repositoryWithAxios('users')
//...
}
inject('repositories', repositories)
}
Further read: Organize and decouple your API calls in Nuxt.js
I will an example of a service layer implementation for my portfolio to create my dashboard that shows some statics about my github and stackoverflow profiles, to do this i created a folder called services inside the project root :
pages
services
|_AxiosConfig.js
|_GitHubService.js
|_StackoverflowService.js
...
in the AxiosConfig.js file i put i created an axios instance with its configuration :
import axios from 'axios';
const clientAPI = url =>
axios.create({
baseURL: url,
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
export default clientAPI;
then in my GitHubService.js i imported that axios instance called clientAPI which i used to my requests :
import clientAPI from './AxiosConfig';
const baseURL = 'https://api.github.com';
export default {
getUser(name) {
return clientAPI(baseURL).get('/users/' + name);
},
getRepos(name){
return clientAPI(baseURL).get('/users/' + name+'/repos');
},
getEvents(name,page){
return clientAPI(baseURL).get('/users/' + name+'/events?per_page=100&page='+page);
},
getLastYearCommits(name,repo){
return clientAPI(baseURL).get('/repos/' + name+'/'+repo+'/stats/commit_activity');
}
};
then in my page i used asyncData hook to fetch my data :
import GitHubService from '../../services/GitHubService'
export default {
...
async asyncData({ error }) {
try {
const { data } = await GitHubService.getUser("boussadjra");
const resRepos = await GitHubService.getRepos("boussadjra");
return {
user: data,
repos: resRepos.data
};
} catch (e) {
error({
statusCode: 503,
message: "We cannot find the user"
});
}
}
I wanted to use axios in my service/service.js file, so instead of passing axios, I accessed it directly like this:
export default {
async fetchArticle() {
let response = await $nuxt.$axios.$get('/api-url')
return response
},
}
In Nuxt, if you want to just get the data without keeping it in your store, you could use the asyncData function, which asynchronously loads data (from API calls and the like) and pushes it into the component's data object before rendering.
I am trying to access a prestashop API with vuejs2
<script>
import axios from 'axios'
export default {
data () {
return {
get: [],
errors: []
}
},
created () {
axios({
method: 'get',
url: 'https://myprestashopsite.com/api/categories/?ws_key=J***************Z&filter[id_parent]=5&output_format=JSON'
}).then(response => {
this.get = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
In the web developer console of mozilla I see that my request return a 200 with the data in the response. But I get "Error: Network Error app.js%20line%201266%20%3E%20eval:15:15" catch as an error.
I tried with another API and it worked, so I guess it comes from the prestashop api. (prestashop version 1.7.3.0)
Is there a way to fix this ?
The problem seems to come from axios. I had to add a rule to the server.
I found the solution to this on this thread :
https://github.com/axios/axios/issues/853
There are other solutions I didn't try in this thread if mine doesn't work.
how to add the rule : https://enable-cors.org/server.html