ajax - Vue.js 资源 : http request with api key (Asana)

标签 ajax http-headers vue.js

我正在尝试使用 vue-resource ( https://github.com/vuejs/vue-resource ) 从 Asana api 中提取一些项目,vue-resource 是一个 Vue.js 插件,可以简化 ajax 调用。我正在使用 api key 访问 Asana,但我不知道如何使用 vue-resource 在请求 header 中传递 key 。

在 jQuery 中这有效,使用 beforeSend:

 $.ajax ({
        type: "GET",
        url: "https://app.asana.com/api/1.0/projects?opt_fields=name,notes",
        dataType: 'json',
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "Basic " + "XXXXXX"); 
        },
        success: function (data){
            // console.log(data);
        }
    });

其中 XXXXXX 是 Asana api key + ':' 用 btoa() 转换。 https://asana.com/developers/documentation/getting-started/authentication

无需身份验证,Vue 实例应该可以在 ready 函数中进行简单请求:

new Vue({    
    el: '#asana_projects',    
    data: {
        projects : []
    },    
    ready: function() {
        this.$http.get('https://app.asana.com/api/1.0/projects?opt_fields=name,notes', function (projects) {
            this.$set('projects', projects); // $set sets a property even if it's not declared
        });
    },    
    methods: {
        //  functions here
    }
});

当然,这会返回 401(未授权),因为其中没有 api key 。

在 vue-resource github 页面上,请求还有一个 beforeSend 选项,但即使在那里进行了描述,我似乎也无法找出正确的语法。

我试过了

    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)

我意识到我不够聪明,因为我无法理解文档中的语法,但我们将不胜感激任何帮助!

有人要吗?

最佳答案

也许我遗漏了一些微妙之处,但您不能使用 $get 调用的 options 参数来指定 header 吗?来自文档:https://github.com/vuejs/vue-resource#methods

Methods

Vue.http.get(url, [data], [success], [options])

[...]

Options

[...]

headers - Object - Headers object to be sent as HTTP request headers

[...]

例如:

this.$http.get(
    'https://app.asana.com/api/1.0/projects?opt_fields=name,notes',
     function (projects) {
        this.$set('projects', projects); // $set sets a property even if it's not declared
     },
     {
         headers: {
            "Authorization": "Basic " + "XXXXXX"
         }
     }
);

关于ajax - Vue.js 资源 : http request with api key (Asana),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809627/

相关文章:

javascript - 尝试通过ajax销毁ruby on Rails中关系实体的请求

python - 恢复文件的 HTTP 下载和 HTTP 压缩

javascript - 无法使用 Axios 从 Http POST 请求中获取 header

Vue.js 输入建议在输入聚焦和@click 时可见

google-chrome - [Vue-Response]在 Crome 60 $http get 返回response.data作为字符串而不是json数组

vue.js - 将 props 传递给路由而不需要 URL 参数

c# - Ajax 成功函数返回空数据

jquery - ajax响应总是报错

c# - 带有回车键的文本框行号

java - Resteasy Content-Type 默认值