Attaching data (body) to $http.delete event in VueJS - vue.js

I have the following method in my Vue.JS component:
removeItems (itemsArray) {
this.$http.delete(this.apiUrl, {items : itemsArray})
.then((response) => {
this.msg = response.msg;
});
}
In vue-resource 0.8.0 everything worked fine. After upgrading to 1.0.3 it doesn't. I found in release notes that they deleted body from GET request, which makes sense, but why did the DELETE request stop working?
If they disabled specifying body explicitly in the DELETE request, how do I add it?

Found a solution. Simply add {body:data} to the request:
removeItems (itemsArray) {
this.$http.delete(this.apiUrl, {body: {items : itemsArray}})
.then((response) => {
this.msg = response.msg;
});
}

Related

Gitlab CI: api trigger with axios call not working when using variables

Without the variables the server call works and gitlab is starting the pipeline.
But when I add variables to that call, it errors: "variables needs to be a map of key-valued strings".
This is my code:
axios
.post(`https://gitlab.myurl.com/api/v4/projects/${projectId}/trigger/pipeline`, {
ref: branch,
token: token,
variables: { STAGING_AREA: 'testing1', NOTIFY_STATUS: true, SLACK_USER_ID: 'xxxxx' }
})
.then(res => {
console.log('pipeline started:', res.data.web_url);
})
.catch(error => {
console.error('errorMessage', error);
});
What is the correct syntax for passing variables?
According to the docs, variable parameter should be in the form of variables[key]=value.
And the request is a multipart request so you need to use FormData.
Try running this code.
const pipelineTriggerBody = new FormData();
pipelineTriggerBody.append('ref', 'master'); // branch name
pipelineTriggerBody.append('token', 'CI_TOKEN');
pipelineTriggerBody.append('variables[STAGING_AREA]', 'testing1');
pipelineTriggerBody.append('variables[NOTIFY_STATUS]', true);
pipelineTriggerBody.append('variables[SLACK_USER_ID]', 'xxxxx');
axios
.post(
`https://gitlab.myurl.com/api/v4/projects/${projectId}/trigger/pipeline`,
pipelineTriggerBody
)
.then(res => {
console.log('pipeline started:', res.data.web_url);
})
.catch(error => {
console.error('errorMessage', error);
});
I was doing one thing wrong.
NOTIFY_STATUS: true
It seems that true can only be passed as a string:
NOTIFY_STATUS: 'true'
After this edit my code worked just fine.

Nuxtjs/Vuejs/Laravel 5.7 API : Component reactive after action/mutation

Maybe you can help me. I searched and tryied lot of things.
I have a Nuxtjs project with Laravel 5.7 API (JWT Auth for the auth).
A user can CRUD a post. Everything works or almost. When the current user create a post, after he is redirected on the page where his posts are indexed. But sometime the new post created appear and sometimes not, I have no error in console logs and server-side the created post is present in database. When I refresh the page, the new post renders. It's very random. Same thing for the delete action.
I use NuxtJs with Vuex for store. I call the action in my component method with dispatch. The action call axios put or delete method and I commit a mutation to update the state.posts array. after dispatch I refetch the user with auth module of NuxtJS to reload the user's posts. and push the route.
Just below the implementation of the delete action to show you my logic.
My component method :
deletePost(post) {
this.$toast.show('Do you really want to remove this post ?', {
duration: 5000,
icon: 'check',
action: [
{
text: 'No',
onClick: (e, toastObject) => {
toastObject.goAway(0)
}
},
{
text: 'Yes',
onClick: (e, toastObject) => {
this.$store.dispatch('posts/deletePost', post).then(() => {
console.log('here')
this.$auth.fetchUser()
this.$router.push({ path: '/:account/posts' })
})
this.$toast.show('Post successfully removed', {
icon: 'check'
})
toastObject.goAway(0)
}
}
]
})
},
The store action :
deletePost({ commit }, post) {
this.$axios
.delete(`/posts/${post.id}`)
.then(res => {
console.log(res.data)
if (res.data.message === 'success') commit('DELETE_POST', post)
})
.catch(err => {
console.log(err)
})
}
The store mutation :
DELETE_POST(state, post) {
const index = state.posts.findIndex(item => item.id === post.id)
state.posts.splice(index, 1)
}
When your are adding or deleting properties of a reactive object, you have to make sure the view updates accordingly. So I think you have to use Vue.delete and Vue.set properties. Please refer https://v2.vuejs.org/v2/api/#Vue-delete and https://v2.vuejs.org/v2/api/#Vue-set
When you are deleting a post from a posts list, your posts list view should be updated accordingly
Edit your DELETE_POST mutation as follows,
DELETE_POST(state, post) {
const index = state.posts.findIndex(item => item.id === post.id)
if (index > -1) {
Vue.delete(state.posts, index);
}
}
Also when you are updating a property of a post do your mutation as follows,
UPDATE_POST(state, updatedPost) {
let index = state.posts.findIndex(post => post.id === updatedPost.id);
if (index > -1) {
Vue.set(state.posts, index, updatedPost)
}
},

vuejs2 get return network error

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

How to add progress event to react-native-fetch-polyfill

I am trying to use react-native-fetch-polyfill becouse of timeout feature for fetch requests but can't implement onProgress event:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('Fetch Error :-S', error);
});
I don't know where to add:
onUploadProgress: function (progressEvent)
That library does not support progress handler. If you need this feature and want to use that library, the simplest thing for you to do would be to fork the library and add the feature yourself:
1) Fork the repository on GitHub.
2) Edit js file in your repository. For example, add callback you need as a third argument to the function:
export default function fetchPolyfill (input, init) {
// becomes
export default function fetchPolyfill (input, init, onUploadProgress) {
// add this somewhere inside
if (onUploadProgress)
xhr.upload.onprogress = onUploadProgress
3) Edit your package json to include
"react-native-fetch-polyfill": "git://github.com/youraccount/react-native-fetch-polyfill"
and run npm install.
1a) Of course you may actually just copy the script and edit it locally on your computer without dealing with GitHub, if you are fine with it not being in node modules. Or download the whole folder and use it as a package.
You can use axios
that already have thus function (onUploadProgress)
Under the hood, fetch uses the React-Native XMLHttpRequest object; this is also true for react-native-fetch-polyfill. This is not the regular xhr object which is used in browsers since the actual requests are sent from the native side.
As far as I know, both RN fetch and react-native-fetch-polyfill do not support upload progress, but you can use XMLHttpRequest directly to do that:
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (progressEvent) => {
//handle progress here, you can use progressEvent.loaded, progressEvent.total to calculate the progress
};
const body = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts');
xhr.send(body);
you can also add the timeout handling yourself:
xhr.timeout = 30 * 1000;
xhr.ontimeout = () => {
//handle timeout here
}

Unable to access `get` method in vue-resource

I have a tiny vue app where I'm wanting to use vue-resource to request an api endpoint.
I've installed vue-resource via npm
I've added the Vue.use(VueResource) lines to my bootstrap file
I've setup my component like this to call the .get method
Blog.vue
...
mounted () {
this.fetchPosts()
},
methods: {
fetchPosts: () => {
debugger;
this.$http.get('my-url')
.then(response => {
console.log(response)
})
}
}
...
I've seen a few github issues and SO posts which touch on this type of problem but most seem to relate to incorrect configuration which I don't think I have (happy to be proven wrong!)
The specific console error I get is:
Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"
What's odd about this is that if you see my debugger line, if I console.log this.$http.get at that point I get:
function (url, options$$1) {
return this(assign(options$$1 || {}, {url: url, method: method$$1}));
}
If I let the code run and then attempt the console.log afterwards I get:
Cannot read property 'get' of undefined
As a result I presume it's some kind of this context issue, but from what I can see the reference should be correct...shouldn't it?
Methods should not be arrows function. The this will not point to the vue instance if a methods is declared using arrow function.
Use normal function instead:
methods: {
fetchPosts(){
debugger;
this.$http.get('my-url')
.then(response => {
console.log(response)
})
}
You can see the warning here