devdropper87
devdropper87

Reputation: 4187

Enabling CORS in backbone

I am new to backbone and am finally making some progress on a small project. I think I am doing the ajax get request properly, but I am now getting this error in the browser:

" XMLHttpRequest cannot load https://api.flickr.com/services/rest/?jsoncallback=?. Method FLICKR.PHOTOS.SEARCH is not allowed by Access-Control-Allow-Methods. "

How do you enable CORS in backbone?

My View:

var PictureView = Backbone.View.extend({
    //the goal of this app is to append HTML to the appID div.  on button click, fetch a random image from flickr.
    el: "#app",


    initialize: function() {
        $('.button').click(function() {
            this.request()
        }.bind(this))
    },

    request: function() {
        console.log('asdfkjsf')

        $.ajax({

            url: "https://api.flickr.com/services/rest/?jsoncallback=?",
            method: 'flickr.photos.search',
            api_key: "mykey",
            format: 'json',
            nojsoncallback: 1,
            per_page: 1,
            success: function(result) {
                console.log(arguments)

                this.$el.append('<img src="' + result + '" />')
            }.bind(this)

        });
    }


})

My Model:

var Picture = Backbone.Model.extend({
    defaults: {

        image: ""
    }

});

Upvotes: 0

Views: 120

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14053

To answer your direct question, you don't enable CORS in Backbone. You (or, more accurately in this case, Yahoo) would enable CORS on the server, e.g. Flickr.

But the problem isn't CORS; you're not using the Flickr API correctly. Those parameters to the $.ajax call are simply wrong. Flickr provides an example URL in their REST documentation.

Even more significantly, you're seriously misusing Backbone by making an API request from a View. That should be done in a Model or a Collection. And, given the specifics above, you don't need to provide your own AJAX call; the standard Backbone.Sync will work fine when provided the correct URL.

I'd suggest taking a step back and spending some time learning about REST APIs and Backbone best practices. There are plenty of tutorials available on the web. Once you're more familiar with those technologies, you'll find it much easier to develop your application.

Upvotes: 1

Related Questions