1

I am developing a backbone application which involves fetching data from an external API. My application's domain is product.site1.com whereas domain of API is api.site1.com.

This is how my model and collection looks

var pModel = new Backbone.Model.extend({});
var pCollection = new Backbone.Collection.extend({
                      model: pModel,
                      url: 'api.site1.com/product'
});

and view looks like the below

var pView = new Backbone.View.extend({
         initialize: function() {
                var _this = this;
                var pCollectionVar = new pCollection();
                pCollectionVar.fetch({
                           dataType: 'jsonp',
                           beforeSend: _this.sendAuthentication,
                           success: function(collection, response, options) {
                                   console.log(collection);
                           },
                           error: function(collection, xhr, options) {
                                   console.log("error");
                           }
                     });
                } 
         sendAuthentication: function(xhr) {
            xhr.setRequestHeader('customKey1', 'ABCD');
            xhr.setRequestHeader('customKey2', '1234');
        }
});

When I execute this, my application makes a get request to the API server, whereas I am not getting the header data at the server end. I don't see these custom headers set for the request in my chrome dev tools either.

EDIT: OPTIONS http://api.site1.com/product 405 (Method Not Allowed) jquery-1.10.2.js:8706

OPTIONS http://api.site1.com/product Invalid HTTP status code 405 jquery-1.10.2.js:8706

XMLHttpRequest cannot load http://api.site1.com/product. Invalid HTTP status code 405 (index):1

These are the errors I am getting while performing the request.

Sreedhar M B
  • 179
  • 4
  • 15

1 Answers1

0

if you want to use sendAuthentication like you do it should be a global function:

pCollectionVar.fetch({
  dataType: 'jsonp',
  beforeSend: sendAuthentication,
  success: function(collection, response, options) {
    console.log(collection);
  },
  error: function(collection, xhr, options) {
    console.log("error");
  }
});

function sendAuthentication(xhr){
   //Code goes here
}

Although this pollutes the global scope, I would use namespace:

var MyApplication = {};
MyApplication.sendAuthentication = function(xhr){ //code inside}.


pCollectionVar.fetch({
  dataType: 'jsonp',
  beforeSend: MyApplciation.sendAuthentication,
  success: function(collection, resp){//rest...}

EDIT:

as described here, jsonp is not an ajax call and can't be treated as such

Community
  • 1
  • 1
ekeren
  • 3,408
  • 3
  • 35
  • 55