add request header on backbone

backbone validation
backbone controller
backbone collection example
backbone js
backbone add to collection
backbone events
backbone el
backbone template

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? Thank you

Models in Backbone retrieve, update, and destroy data using the methods fetch, save, and destroy. These methods delegate the actual request portion to Backbone.sync. Under the hood, all Backbone.sync is doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.

fetch, save, and destroy all accept an additional parameter [options]. These [options] are simply a dictionary of jQuery request options that get included into jQuery ajax call that is made. This means you can easily define a simple method which appends the authentication:

sendAuthentication = function (xhr) {
  var user = "myusername";// your actual username
  var pass = "mypassword";// your actual password
  var token = user.concat(":", pass);
  xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token))));

And include it in each fetch, save, and destroy call you make. Like so:

  beforeSend: sendAuthentication 

This can create quite a bit of repetition. Another option could be to override the Backbone.sync method, copy the original code and just include the beforeSend option into each jQuery ajax request that is made.

Hope this helps!

Using custom headers with Backbone.sync (Example), Extending backbone's requests with custom headers add a sync function on every model and collection and add your custom headers there,� backbone.csrf will make your Backbone application compatible with your backend web frameworks that implements CSRF protecting systems. Module's the only method initialize() configures Backbone.sync() to set X-CSRFToken request header for every requests it sends to make sure that all backbone requests are sent with csrf tokens.

The easiest way to add request header in Backbone.js is to just pass them over to the fetch method as parameters, e.g.

MyCollection.fetch( { headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );

Extending backbone's requests with custom headers, But in minified version all request sends without header. Why? var originalSync = Backbone.sync; Backbone.sync = function(method, model,� It is a request header that indicates the request's mode to a server. It is a Structured Header whose value is a token with possible values cors, navigate, nested-navigate, no-cors, same-origin, and websocket. Sec-Fetch-User It is a request header that indicates whether or not a navigation request was triggered by user activation.

One option might be to use the jQuery ajaxSetup, All Backbone requests will eventually use the underlying jQuery ajax. The benefit of this approach is that you only have to add it one place.

    headers: { 'Authorization' :'Basic USERNAME:PASSWORD' }

Edit 2nd Jan 2018 For complex web applications this may not be the best approach, see comments below. Leaving the answer here for references sake.

How to inject custom header in all ajax requests? � Issue #175 , Contribute to fiznool/backbone.basicauth development by creating an A resource protected with HTTP Basic Authentication requires the following HTTP header to be Re-introduced concept of setting Basic Auth credentials from a function,� Would be nice for this to actually work, and to have the ability to more easily specify custom headers for what is a pretty common scenario. @RaMin0 After being stuck as well, the laziest that I am able to get is to use the Presets option on the Headers tab for each individual request. cc [@]mauricewijniaa (cant mention more than 2 people as a new user apparently)

You could override Backbone sync method.

_sync = Backbone.sync
Backbone.sync = (method, model, options) ->
    options.beforeSend = (xhr) ->
        xhr.setRequestHeader('X-Auth-Token_or_other_header' , your_hash_key)
        #make sure your server accepts X-Auth-Token_or_other_header!!
    #calling the original sync function so we only overriding what we need this, method, model, options )       

fiznool/backbone.basicauth: HTTP Basic Authentication for , 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? A pointer to a string variable that contains the headers to append to the request. Each header except the last must be terminated by a carriage return/line feed (CR/LF). dwHeadersLength. An unsigned long integer value that contains the length, in characters, of pwszHeaders.

    headers: {'Authorization' :'Basic USERNAME:PASSWORD'}

This code set headers to Backbone ajax, so they will be sent with every Backbone.sync. You will be able to send headers without using xhr.setRequestHeader with every sync call.

So you don't need to do the following every time:

MyCollection.fetch({ headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );

You can just do


Maybe it's kind of hack but it works perfectly for my system.

add request header on backbone, CORS headers aren't supported by Opera and IE 6/7. Host the codebase on a simple HTTP server such that the domain is localhost with port 80 hidden. This wraps up setting up the client, there are some notable points to make sure this� Request header. The request URI is bundled in the request message header, along with any additional fields required by your service's REST API specification and the HTTP specification. Your request might require the following common header fields: Authorization: Contains the OAuth2 bearer token to secure the request, as acquired earlier from

Cross-domain Backbone.js with sessions using CORS, You can report bugs and discuss features on the GitHub issues page, or add with a HTTP POST, setting the X-HTTP-Method-Override header with the true� Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Backbone.js, Setting this option will fake "PATCH" , "PUT" and "DELETE" requests via the _method parameter and set a X-Http-Method-Override header. Backbone. By default, a Lambda function only ingests the request body received by an API Gateway API. To pass custom headers from an API Gateway API to a Lambda function, use curl to send a message to the API using a body mapping template to extract any custom headers added to the message.

backbone.js, When integrating Backbone.js in your Rails App, you might face the problem of the beforeSend; // Set X-CSRF-Token HTTP header options. - Add / modify / remove request headers and response headers (you can use this to set X-Forwarded-For, Authorization, Access-Control-Allow-Origin: *) - Conditionally enable header modification based on URL and/or resource type - Add comments to header - Multiple different profiles - Sorting headers and name, value, or comments - Append value to

  • tried your code. but there's no response. it doesn't call the service.
  • No response at all? Or are you receiving a 401 response code?
  • nope. anyways. can you give me a sample code on how to override the backbone.sync to headers?
  • Can you provide an example of the backbone.js code that you wrote for this implementation? I'm having a problem getting it to work. You can see my progress in this question
  • I wouldn't copy the original Backbone.sync method. You can do something like what's suggested in…, but basically just override options, and call, options).
  • This worked for me, surprisingly! And it's not in the docs by the time I'm typing just if anyone wondered. Extremely simple way to handle it ;) amazing. >thanks!
  • that works unless username has a : in it, you really should base64 encode username:password
  • While it looks like it could work, don't use this for the reasons I described in another answer.
  • I'd be inclined to agree, my answer is pretty old now. The only thing I would say is if you are working on a simple experiment with one data source this would be a quick way of getting going. So I might leave it here for reference.
  • Perhaps you could give an explanation as to how this answers the question?
  • It is a hack that shouldn't be used for reasons explained in another answer of mine. It's also the same answer as the $.ajaxSetup one above.
  • Is there a way to define the response interceptor? Something like ajaxError?