I'm learning VueJS / Express and I'm trying to display data from an external API onto my page. I'm using Express as the API Calls require headers + I believe its safer to keep it separate from Vue.
Here is my Express
app.get('/summoner', function(request, response) {
axios.get('https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/XXXXXXXX', {headers: headers})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
})
Here is my Vue code:
import axios from 'axios'
export default {
name: 'summoner',
data () {
return {
summoner: [],
errors: []
}
},
created () {
console.log('Created')
axios.get('/api/summoner')
.then(response => {
console.log('Hit me')
this.summoner = response.data
})
.catch(e => {
this.errors.push(e)
console.log(e)
})
}
}
The console.log(response.data) is showing me the object I expect which is:
{ id: XXXXXXXX,
accountId: XXXXXXXX,
name: 'XXXXXXXX',
profileIconId: XXXXXXXX,
revisionDate: XXXXXXXX,
summonerLevel: XXXXXXXX }
The console.log('Hit Me') is never fired
The console.log('Created') is fired on page load.
Nothing I seem to try allows me to display any of the object using Vue e.g:
{{ summoner.id }}
Just to add, I have configured a proxy in webpack which forwards the below requests to Express. As far as I can tell, this is working as each time I refresh the page, I see the ExpressJS console.log(response.data) fire
Could anyone help?
Thanks!
In your express code you do not return the repsonse (which you also override in the axios response). Try changing it to
app.get('/summoner', function(request, res) { // <--- careful here is a change
axios.get('https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/XXXXXXXX', {headers: headers})
.then(response => {
console.log(response.data)
return res.status(200).send(response.data);
})
.catch(error => {
console.log(error)
return res.status(400).send(error);
})
})
I actually resolved this by doing:
res.json([response.data])
In the ExpressJS side of things.
I also had to use response.data[0] within Vue.
Related
how can i avoid the data blink after update store data?
you can see the effect here:
https://drive.google.com/file/d/178raL6AJiC4bpIOImnaTKh6Yf9GruTCz/view?usp=sharing
component:
[...]
mounted() {
this.getIdeasFromBoard(this.$route.params.board_id);
},
[...]
store:
[...]
const actions = {
getIdeasFromBoard({ commit, dispatch }, board_id) {
apiClient
.get('/ideas/' + board_id)
.then((result) => {
console.log('success');
commit("SET_IDEAS_BOARD", result.data);
})
.catch(error => {
console.log('error' + error);
alert("You have failed to log in. Try again with another credentials.");
dispatch('auth/logout', null, { root: true });
this.$router.push({ name: "public" });
});
},
[...]
i've searched some simple tutorial about consuming api with error handling, but didnt find it.
thanks
It's because IDEAS_BOARD has the previous data until the new API call is completed. You would need to display a loader or a blank screen until the API call for the selected board is completed.
From actions, return a promise so that your component knows when is the call completed.
getIdeasFromBoard({ commit, dispatch }, board_id) {
return new Promise((resolve, reject) => {
apiClient
.get('/ideas/' + board_id)
.then((result) => {
console.log('success');
commit("SET_IDEAS_BOARD", result.data);
resolve()
})
.catch(error => {
console.log('error' + error);
alert("You have failed to log in. Try again with another credentials.");
dispatch('auth/logout', null, { root: true });
this.$router.push({ name: "public" });
reject()
});
})
},
In your .vue component,
async mounted () {
this.loading = true // some flag to display a loader instead of data
await this.$store.dispatch()
this.loading = false
}
There must be some other ways too like having this loading flag in the Vuex store. But it depends on you
I try to create a baseURL from .env.local, but in request I get http://localhost:8083/Contracts/users insted of https://api.EXAMPLE.dev/api/users.
I use npm run serve -> http://localhost:8083
Any suggestion, please?
.env.locale
VUE_APP_ENDPOINT="https://api.EXAMPLE.dev/api"
main.js
import axios from "axios";
axios.defaults.baseURL = process.env.VUE_APP_ENDPOINT;
Component.vue
created: function() {
axios
.get("/users")
.then(response => {
this.items = response.data;
})
.catch(error => {
console.log(error);
});
},
Try writing
axios.defaults.baseURL = process.env.VUE_APP_ENDPOINT || "https://api.EXAMPLE.dev/api"
And for Component.vue file
created: function() {
axios({
url: "/users"
})
.then(response => {
this.items = response.data;
})
.catch(error => {
console.log(error);
});
}
Check if this works. May be that can be reason that process.env is not giving correct value.
Was no problem with the code, after a restart it worked.
npm run serve
I am new to vuejs. I am having trouble deleting json data from a fakeserve by using axios.delete().
I tried doing this :-
axios.delete('http://localhost:3000/users/', {params: {id: this.idToDelete} })
.then((response) => {
console.log(response)
}, (error) => {
console.log(error)
})
This is my html:-
<v-text-field v-model="idToDelete" type="number" hide-details outline
label="Enter Id to delete"></v-text-field>
<v-btn #click="userIdtoDelete()" color="error">Delete</v-btn>
This is my javascript (src/views/pages/Delete.vue):
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
export default {
data () {
return {
idToDelete: ''
}
},
methods: {
userIdtoDelete () {
axios.delete('http://localhost:3000/users/', {params: {id: this.idToDelete} })
.then((response) => {
console.log(response)
//alert('response = ' + response)
}, (error) => {
console.log(error)
//alert('error = ' + error)
})
}
}
}
My code is in https://github.com/boidurja/users.git
And fakeserver is in https://github.com/boidurja/fakeserver.git
When I click the delete button data is not getting deleted and I am getting the following error message:-
DELETE http://localhost:3000/users/?id=3 404 (Not Found)
JSON Server automatically creates routes in a RESTful format, eg
GET /users
GET /users/1
POST /users
PUT /users/1
PATCH /users/1
DELETE /users/1
So with that in mind, you should be using
axios.delete(`http://localhost:3000/users/${encodeURIComponent(this.idToDelete)}`)
.then(res => { console.log(res) })
.catch(err => { console.error(err) })
I think your issue is that you are calling a function inline with () vue does this for you, try
<v-btn #click="userIdtoDelete" color="error">Delete</v-btn>
I think you are triggering the function twice.
In addition, you can try instead of using v-model to catch the id directly in the function like userIdtoDelete($event.target.value)
i post from vuejs cli with axios to nodejs express server:
axios.post('http://localhost:8081/users', bar)
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error)
})
and server:
app.post('/users', (req, res) => {
console.log(req.body.bar)
res.json(req.body.bar)
})
in http://localhost:8081/users i got Cannot GET /users and console log windows: undefined
please help me!
axios.post('http://localhost:8081/users', {foo: "Bar"})
.then((response)=> {
console.log(response.data) // must be show "Bar"
})
.catch((error)=> {
console.log(error)
})
app.post('/users', (req, res) => {
console.log(req.body.foo) // must be show "Bar"
res.send(req.body.foo)
})
I have an AddComment.vue component which has a form, on submit it hits a laravel api endpoint where validation happens. If validation fails I want to show the errors in AddComment.vue. How can return the error.response object to AddComment.vue? Currently, I can see 'fired' in the console when I want to be logging the error. Where am I going wrong any help would be greatly appreciated
AddComponent.vue
methods: {
addComment() {
this.$store.dispatch('addComment', {
name: this.name,
email: this.email,
body: this.body
})
.then(response => {
this.$router.push({ name: 'home' })
console.log('fired')
})
.catch(error => {
console.log(error)
})
},
}
store.js
actions: {
addComment(context, comment) {
new Promise((resolve, reject) => {
axios.post('/comments', {
name: comment.name,
email: comment.email,
body: comment.body,
approved: false
})
.then(response => {
context.commit('addComment', response.data)
resolve(response)
})
.catch(error => {
reject(error)
})
});
},
}
The catch() block only gets called if the Laravel backend throws an error. So if you are returning a normal status code of 2xx then axios always calls the .then() part. In that case, you have to resolve the error message yourself.
Try something like this in your backend route (it will return an error):
return response()->toJson([
'message' => 'error message',
], 500);
And see if this responds with an actual error in you vuejs application.