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)
Related
I have been struggling with this issue for a day now. I want to make a copy of the store for user into userCopy so that it can be edited by the user without causing a mutation. My problem is that even though I am using the mounted hook, userCopy only returns an empty store state.
pages/settings/_id.vue
<template>
<div>
{{ user }} // will display the whole object
{{ userCopy }} // will only display empty store object
</div>
</template>
<script>
import { mapState } from 'vuex'
import _ from 'lodash'
data() {
return {
userCopy: {}
}
},
computed: {
...mapState({ user: (state) => state.staff.user })
},
created() {
this.$store.dispatch('staff/fetchUser', this.$route.params.id)
},
mounted() {
this.$data.userCopy = _.cloneDeep(this.$store.state.staff.user)
},
</script>
store/staff.js
import StaffService from '~/services/StaffService.js'
export const state = () => ({
user: {
offers: '',
legal: ''
}
})
export const mutations = {
SET_USER(state, user) {
state.user = user
},
}
export const actions = {
fetchUser({ commit, getters }, id) {
const user = getters.getUserById(id)
if (user) {
commit('SET_USER', user)
} else {
StaffService.getUser(id) // StaffService users axios get call
.then((response) => {
commit('SET_USER', response.data)
})
.catch((error) => {
console.log('There was an error:', error.response)
})
}
},
}
export const getters = {
getUserById: (state) => (id) => {
return state.staff.find((user) => user.id === id)
}
}
Even using this mounted method did not solve the issue. The userCopy object still returns empty.
mounted() {
this.$store
.dispatch('staff/fetchUser', this.$route.params.id)
.then((response) => {
this.userCopy = this.$store.state.staff.user
})
},
It seems that the mounted() is called before your network request get solved.
To fix this, I suggest to do like this.
First:
if (user) {
console.log('user found',user)
commit('SET_USER', user)
return user
} else {
console.log('user not found')
//RETURN the Axios Call here
return StaffService.getUser(id) // StaffService users axios get call
.then((response) => {
commit('SET_USER', response.data)
//return the response here, after committing
return response.data
})
then in your component
mounted() {
this.$store
.dispatch('staff/fetchUser', this.$route.params.id)
.then((response) => {
console.log(response)
this.userCopy = response
})
}
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 trying to do a GET request using Axios , but get the following error in console:
TypeError: Cannot set property 'films' of undefined
at eval (SearchBar.vue?e266:26)
SearchBar.vue
<template>
<section>
<input v-model='film' type='text' list='films'>
<datalist id='films'>
<option v-for='film in films' :key='film.episode_id'>{{film}}</option>
</datalist>
</section>
</template>
<script>
import axios from "axios";
export default {
name: "SearchBar",
data() {
return {
film: "",
films: []
};
},
created() {
axios
.get("https://swapi.co/api/films/")
.then(function(response) {
// handle success
//console.log(response);
this.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
};
</script>
Anyone can tell me why I get the error? Note: I am running this locally for instant prototyping via Vue-Cli
One way is to use Arrow function:
created() {
axios
.get("https://swapi.co/api/films/")
.then((response) => {
// handle success
//console.log(response);
this.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
2. Another way that = this & then use that inside promise callback
created() {
const that = this; // <-- assign this in that
axios
.get("https://swapi.co/api/films/")
.then(function (response) {
// handle success
//console.log(response);
that.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
I use Nuxt.js and I have dynamic page /items/{id}:
<template>
<div>
<h1>Item #{{ item.id }} «{{ item.title }}»</h1>
</div>
</template>
<script>
import { api } from '../../mo/api'
export default {
asyncData({ params }) {
return api(`items/${params.id}`)
},
}
</script>
Backend API returns object {item: {id: .., title: "...", ...}}.
But if an item with specified ID not exist API returns 404 response.
And Vue crash with "[Vue warn]: Property or method "item" is not defined on the instance but referenced during render."
How can I handle 404 response?
My api.js module:
import axios from 'axios'
export function api(url) {
url = encodeURIComponent(url)
return axios
.get(`http://localhost:4444/?url=${url}`)
.then(({ data }) => {
return data
})
.catch((err) => {
// 404 catch there
})
}
Solution:
Need to read manual: https://nuxtjs.org/guide/async-data/#handling-errors
just execute error function :)
<script>
export default {
asyncData({ params, error }) {
return axios
.get(`https://my-api/posts/${params.id}`)
.then((res) => {
return { title: res.data.title }
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
},
}
</script>
If you're using the fetch() hook, this is how it should be written
<script>
export default {
async fetch() {
try {
await fetch('https://non-existent-website.commmm')
.then((response) => response.json())
} catch (error) {
this.$nuxt.context.error({
status: 500,
message: 'Something bad happened',
})
}
},
}
</script>
More context available here: https://nuxtjs.org/announcements/understanding-how-fetch-works-in-nuxt-2-12/#error-handling
Need to read the manual: https://nuxtjs.org/guide/async-data/#handling-errors :) .
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.