add request header on backbone

后端 未结 10 2150
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 08:46

My server has a manual authorization. I need to put the username/password of my server to my backbone request inorder for it to go through. How may i do this? Any ideas? Tha

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 09:17

    Try to use it. We can use either

    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRFToken', csrf_token);
    },
    

    or

    headers: {
        "X-CSRFToken": csrf_token
    },
    

    But I would recomment the first option(beforeSend).

    Here is the working code snippet in my case.

    var csrf_token = this.getCSRFToken();
    self.collection.fetch(
    {
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRFToken', csrf_token);
        },
        // headers: {
        //     "X-CSRFToken": csrf_token
        // },
        data: {
            "mark_as": "read"
        },
        type: 'POST',
        success: function () {
            if (clickLink) {
                window.location.href = clickLink;
            } else {
                self.unreadNotificationsClicked(e);
                // fetch the latest notification count
                self.counter_icon_view.refresh();
            }
        },
        error: function(){
            alert('erorr');
        }
    });
    

提交回复
热议问题