jquery - Kendo 自动完成授权 header

标签 jquery ajax kendo-ui

我不明白为什么我的 Kendo Autocomplete 小部件没有将请求中的授权 header 发送到服务器:

var dataSource = new kendo.data.DataSource({
    type: 'odata',
    serverFiltering: true,
    transport: {
        read: {
            url: myApiUrl,
            type: 'GET',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', myAuthorizationValue);
            }
        }
    }
});

$('#myAutocompleteField').kendoAutoComplete({
    dataTextField: 'fieldName',
    filter: 'contains',
    minLength: 3,
    dataSource: dataSource
});

当我在开发工具中检查服务器响应时,我从服务器收到 401 Unauthorized 错误。查看请求 header ,我根本看不到 Authorization 属性。

我需要做什么才能将授权 header 包含在请求中?

更新:

我一直在探索这个问题。如果我只是使用与 Kendo DataSource 参数中的 transport.read 相同的对象执行典型的 $.ajax 请求,它会发送 header ,并且我会获得成功的响应。

$.ajax({
    url: myApiUrl,
    type: 'GET',
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', myAuthorizationValue);
    },
    success: function(res) {
        console.log('success!');
        console.log(res);
    }
});

最佳答案

根据this forum post on Telerik forum ,当使用 type: 'odata' 时,服务器期望使用 JSONP 并且不会发送 Auth header 。

注释掉该行,如下所示,将发送 Auth header ,但它使用过滤器数组发送搜索查询,而不是典型的 ODATA 参数(这是有道理的):

var dataSource = new kendo.data.DataSource({
    //type: 'odata',  // this causes the auth headers to not be sent
    serverFiltering: true,
    transport: {
        read: {
            url: myApiUrl,
            type: 'GET',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', myAuthorizationValue);
            }
        }
    }
});

// Parameters sent
filter[filters][0][value]:sprint
filter[filters][0][operator]:contains
filter[filters][0][field]:fieldName
filter[filters][0][ignoreCase]:true
filter[logic]:and

有趣的是,我在互联网上的其他地方发现有人使用 type: 'odata-v4',它确实发送了 Auth header 并正确发送了 ODATA 过滤器参数。

var dataSource = new kendo.data.DataSource({
    type: 'odata-v4',
    serverFiltering: true,
    transport: {
        read: {
            url: myApiUrl,
            type: 'GET',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', myAuthorizationValue);
            }
        }
    }
});

// Parameters Sent
$format:json
$filter:contains(tolower(fieldName),'sprin') // sprin is the search string
$count:true

关于jquery - Kendo 自动完成授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789747/

相关文章:

c# - 如何将 gridview 中的货币舍入到有效数字?

javascript - Unslider(JS 问题?)在页面刷新时中断

jquery - 在窗口完全加载innerHTML后加载processing.js sketch?

javascript - 如何在jsp中访问javascript值?

javascript - 如何在 Kendo UI Scheduler 上显示自定义事件?

javascript - 在没有 jQuery 的情况下防止双击缩放

javascript - 更改变量 onclick 的值

javascript - Rails 正在渲染部分 View ,而它应该只更新现有页面中的部分 View

kendo-ui - Kendo UI MVC 将 MultiSelect 数据值发送到 Action 方法

javascript - Kendo 工具提示相对于鼠标位置?