Search code examples
vue-resourcevuejs2

Vue-Resource, can't get this.$http.post working in Vue instance


I am trying to post some data usng this.$http.post and I could not figure out how to pass in the data through the route api..

new Vue({

    el: '#root',

    data: {
        newName: '',
        nameList: []
    },

    methods: {
        addName(){
            this.nameList = this.nameList.concat(this.newName);
            var name = this.newName;
            this.newName = '';

            this.$http.post('/api/name', {name: name}).then((response) => {
                console.log(response.message);
            });
       }
    },

    mounted(){
        this.$http.get('/api/name').then((response) => {
            this.nameList= this.nameList.concat(JSON.parse(response.body));
            console.log(this.nameList);
        });
    }


});

Solution

  • It is not very clear, what is the exact issue, here, what exact API you are trying to hit.

    If you are trying to hit: /api/name/:someName, you can do following

    this.$http.post('/api/name/'+name ).then((response) => {
       console.log(response.message);
    });
    

    If you are trying to hit: /api/:someName with payload, you can do following

    this.$http.post('/api/' + name, {name: name}).then((response) => {
       console.log(response.message);
    });
    

    Let me know if it helps.