在骨干网中放置自定义http标头

Jua*_*ado 8 http backbone.js tastypie

我正在使用Tastypie创建API,我想从Backbone访问API.要发送凭据,我使用user_id和api_key.我在android和curl中这样做,这工作很棒,但我可以设置骨干的http标头.

在卷曲我使用:

 curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -H "user_id: 32" -H "api_key: 69950" -X DELETE "http://127.0.0.1:8000/api/v1/deletenote/66/?format=json" 
Run Code Online (Sandbox Code Playgroud)

在android java中我使用:

    HttpDelete requestDELETE = new HttpDelete();
    requestDELETE.setHeader("Content-type", "application/json");
    requestDELETE.setHeader("Accept", "application/json");
    requestDELETE.setHeader(Constants.HEADER_USER_ID, user_id);
    requestDELETE.addHeader(Constants.HEADER_API_KEY, key);
Run Code Online (Sandbox Code Playgroud)

Both of them work great, but when I try this in Backbone following the responses that I found in other post from the page, this didn't work.

I am trying this:

var removeNote = new DeleteNoteModel({id:this.model.toJSON().id},{ query:this.model.toJSON().id});


removeNote.destroy({ 
        headers: {'user_id':dataWeb.get("id"),'api_key':dataWeb.get("api_key")}
        },{
                    async:false,
                    error: function(model, response){
                        console.log("KO_REMOVE_NOTE");
                        console.log(response);
                    },
                     success : function(model, response){
                        console.log("OK_REMOVE_NOTE");
                        console.log(response);
                     }
                }
    );
Run Code Online (Sandbox Code Playgroud)

I'm putting the header when I call to the destroy call, but this don't send anithing to the server.

What I am doing in a wrong mode?

Thanks to all.

Tom*_* Tu 19

Tallmaris的答案应该为你解决,虽然我会建议使用jQuery ajaxSetup方法将标题设置为所有ajax请求的默认值,因为我相信你总是需要它们吗?

在某个地方启动App放入

$.ajaxSetup({
    headers: {
        'user_id':dataWeb.get("id"),
        'api_key':dataWeb.get("api_key")
    }
});
Run Code Online (Sandbox Code Playgroud)

多亏了你,你将为自己节省很多重复的代码:)保持干燥!

(显然,您需要确保在启动应用程序的范围内提供dataWeb :))