mardi 4 août 2015

Vue.js-resource: http request with api key (Asana)

I'm trying to extract some projects from the Asana api with vue-resource (http://ift.tt/1JQsHqO), a Vue.js add-on that makes ajax calls simple. I'm using an api key to access Asana, but I can't figure out how to pass the key in the request header using vue-resource.

In jQuery this works, using beforeSend:

 $.ajax ({
        type: "GET",
        url: "http://ift.tt/1HnFw6b",
        dataType: 'json',
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "Basic " + "XXXXXX"); 
        },
        success: function (data){
            // console.log(data);
        }
    });

Where XXXXXX is the Asana api key + ':' converted with btoa(). http://ift.tt/1HnFw6d

Without needing to authenticate, the Vue instance should be fine with a simple request in the ready function:

new Vue({    
    el: '#asana_projects',    
    data: {
        projects : []
    },    
    ready: function() {
        this.$http.get('http://ift.tt/1HnFw6b', function (projects) {
            this.$set('projects', projects); // $set sets a property even if it's not declared
        });
    },    
    methods: {
        //  functions here
    }
});

This, of course, returns a 401 (Unauthorized), since there is no api key in there.

On the vue-resource github page there is also a beforeSend option for the request, but even though it is described right there I can't seem to figure out the correct syntax for it.

I have tried

    this.$http.get( ... ).beforeSend( ... ); 
    // -> "beforeSend is not a function", and

    this.$http.get(URL, {beforeSend: function (req, opt) { ... }, function(projects) { //set... });
    // -> runs the function but req and opt are undefined (of course)

I realize I'm being less than clever as I fail to understand a syntax that is right there in the documentation, but any and all help would be much appreciated!

Any takers?

Aucun commentaire:

Enregistrer un commentaire