未捕获(承诺)TypeError:无法读取未定义的axios的属性“ push”

时间:2020-08-01 21:44:41

标签: django vue.js axios

我正在尝试将书籍收集在书架中。但是,当我尝试添加一本书时,该页面不执行任何操作,并且在控制台中出现此错误“未捕获(承诺)TypeError:无法读取未定义的属性'push'” 。需要帮助。

main.js

function sendRequest(url,method,data) {
    var r = axios({
        method: method,
        url: url,
        data: data,
        xsrfCookieName: 'csrftoken',
        xsrfHeaderName: 'X-CSRFToken',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    return r
}

var app = new Vue({
    el : '#app',
    data:   {
        book: '',
        books:  [
            {title: 'one'},
            {title: 'two'}
        ]
    },
    
    created(){
        var vm = this;
        var r = sendRequest('','get')
            .then(function(response){
                vm.books = response.data.books; 

            })


    },
    methods: {
        createBook(){
            var vm = this;
            var formData = new FormData();
            formData.append('title', this.book);

            sendRequest('','post',formData)
                .then(function (response) {
                    vm.books.push(response.data.book); //PROBLEM HERE
                    vm.book = '';

                })
        }
    }

})

views.py

def add_book(request, shelf_id):
    context = {}
     if request.POST:
        shelf = get_object_or_404(Shelf, pk=shelf_id)
        book_form = BookCreation(request.POST)
        temp = book_form.save(commit=False)
        temp.shelf = shelf
        temp.save()
        if book_form.is_valid():
            books = book_form.save()
            return JsonResponse({'book': model_to_dict(books)},status=200)
    return render(request, 'shelf/addBook.html')

url.py

path('<int:shelf_id>/create_book', add_book, name='addbook'),

1 个答案:

答案 0 :(得分:0)

显然,问题出在我的后端,如果使用if request.POST而不是request.method =='POST'。

def add_book(request, shelf_id):
    context = {}
     if request.method == 'POST': //THIS IS WORKING CODE
        shelf = get_object_or_404(Shelf, pk=shelf_id)
        book_form = BookCreation(request.POST)
        temp = book_form.save(commit=False)
        temp.shelf = shelf
        temp.save()
        if book_form.is_valid():
            books = book_form.save()
            return JsonResponse({'book': model_to_dict(books)},status=200)
    return render(request, 'shelf/addBook.html')