user6385799
user6385799

Reputation:

Axios and vue-resource put method doesn't work

I have on front vuejs and on backend java. In one component I bring the users from the database.

Users.vue

getUsers() {
  this.$http.get("/user")
    .then((response) => {
      this.users = response.data.users;
    })
}

Still here I use v-for to bring all users in another component User.vue.

<app-user v-for="user in users" :user="user" :key="user.index"></app-user>

In user component I have a router link that takes me to another page where I can edit the username.

User.vue

 <p class="user-name">{{user.firstName}}</p>
 <router-link :to="'/users/edit-user/'+user.id">
    <a ><i class="ti-pencil-alt" aria-hidden="true"></i></a>
 </router-link>

EditUser.vue

    <template>
      <input type="text" :value="user.firstName" v-model="userInfo.firstName">
    </template>
    <script>
    export default {
      data() {
        return {
          user: {},
          userInfo: {
            firstName: '',
          }
        }
      },
      created() {
        this.getUsers();
      },
      methods: {
        getUsers() {
          this.$http.get("/user/" + this.$route.params.id)
            .then((response) => {
              this.user = response.data;
            })
        },
        updateUser() {
          axios.put('/user', this.userInfo,  
            {'headers':{'X-AUTH-TOKEN':localStorage.token}},
            {'headers':{'Content-Type': 'application/json'}})
          .then((response) => {
            console.log("Success! You edited the user"); 

          })
          .catch((response) => {
            console.log('Error in edit');
          })
        }
      },
    }
    </script>

I started learning vuejs a month ago and still have to learn :).

In the input I use :value="user.firstName" to bring the value for firstName that already exists. I try to use v-model="userInfo.firstName" to get new value for userName, but when I put this, the value, that existed already, disappears from the input.

To save data with post works fine but only with axios. I don't know why post doesn't work with vue-resource. So I tried put with axios too, but what I edit when I press save button, on EditUser.vue, my request doesn't go to server.

I say this because I saw that in the backend I don't get any error, nothing, but if I use post or get I can get or save users.

What do I do wrong in my code that I don't edit the user?

Upvotes: 0

Views: 3840

Answers (1)

Imre_G
Imre_G

Reputation: 2535

There seems to be nothing wrong with your axios implementation. Seems to me that you are updating to the general /users/ route. This works for post, since no user id exists yet, so a new one will be created. However, if you use PUT, a user id does exist. So I think you should modify your endpoint to be /user/:userid instead of just /user. Hopes this helps.

From restapitutorial dot com/lessons/httpmethods.html:

Examples:

Upvotes: 1

Related Questions