Patch request in vuejs axios jwt | extrovert.dev -->

Patch request in vuejs axios jwt

Patch request in vuejs axios jwt
Saturday, December 26, 2020

Why patch instead of post request? Patch request is helpful when you need to replace the existing resource partially. For Instance, when updating a single field of resource, sending complete API resource to the server is clunky. Let me make it easy, for example, there is a user profile model having a username, email, and avatar as fields. Now let's say the user might want to update his avatar, In this case, we don't want to send the entire model fields since it makes a heavy request, instead, we update only the avatar field. The patch makes it easy for us.

Patch request in vuejs axios jwt


Let's create an input field within the template

<v-btn
color="green"
x-small
<!-- v-show="!$store.state.authUser.avatar" Iam using vuex to show the button when user is having no avatar-->
outlined
:loading="isSelecting"
@click="onButtonClick"
>
<v-icon left>mdi-cloud-upload-outline</v-icon>upload picture
</v-btn>
<input
type="file"
ref="uploader" <!-- using refs to reference it to above button -->
class="d-none"
accept="image/*"
@change="uploadImage($event)"
id="file-input"
/>
view raw apppatch.vue hosted with ❤ by GitHub

Now create methods for button click and upload Image event.

methods: {
uploadImage(event) {
let img = new FormData();
img.append("avatar", event.target.files[0]);
const base = {
baseURL: this.$store.state.endpoints.baseUrl,
headers: {
// JWT token !!!
Authorization: `JWT ${this.$store.state.jwt}`,
"Content-Type": "multipart/form-data"
},
xhrFields: {
withCredentials: true
}
};
const axiosInstance = axios.create(base);
axiosInstance({
url: "http://127.0.0.1:8000/userDetails/",
data: img,
method: "patch"
})
.then(response => {
console.log(response);
this.snackbar = true
})
.catch(error => {
console.log(error);
console.debug(error);
console.dir(error);
});
},
onButtonClick() {
this.$refs.uploader.click();
}
},
view raw appach.js hosted with ❤ by GitHub

Here avatar is the API name field holding the avatar url.

Thanks for reading !! 


 


wb_incandescent You may like

1 Response to Patch request in vuejs axios jwt