【问题标题】:Basic Authentication using jQuery/ajax使用 jQuery/ajax 的基本身份验证
【发布时间】:2016-01-01 18:45:22
【问题描述】:

我正在尝试创建基本身份验证页面,其中我的表单具有三个字段

  1. 用户名
  2. 密码
  3. 授权类型

在提交表单时,我只想在我的 HTML 上以 JSON 格式显示来自服务器的返回响应。 我对 Web 服务的 AJAX 调用还需要设置 Authorization 标头。 但不知何故,标题没有设置。我正在尝试

 beforeSend : function(xhr)
   {
       xhr.setRequestHeader('Authorization', "Basic ******");
       xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
    }

但是当我在控制台中调试代码时,似乎断点永远不会进入这个函数。 我是 Ajax 的新手,并通过在互联网上搜索来尝试以下代码。 我在下面发布整个代码。

代码:

$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        // get the form data
        var formData = {
            'username': $('#username').val(),
            'password': $('#password').val(),
            'grant_type': $('#grantType').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', 
            url         : 'http://localhost:9090/oauth/token', 
            beforeSend: function (xhr)
            {
                xhr.setRequestHeader("Authorization", "Basic ******");
                xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
            },
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
                        encode          : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 
                alert(data);

                // here we will handle errors and validation messages
            })

            .fail(function (jqXHR, textStatus){
                alert('Status : ' + textStatus + '' + JSON.stringify(jqXHR));
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

导致我的代码中没有设置标题的原因。 请纠正我。

在“网络”选项卡的控制台(Google Chrome)中,我可以看到下面的请求标头

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type, contenttype
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.1.128:9090
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

以下错误出现在控制台中。

当从 Google Chrome 的 Advanced Rest Client 扩展程序调用相同的 API 时,它会显示所有标题

User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
contentType: application/json;charset=UTF-8
Authorization: Basic **********
Content-Type: application/x-www-form-urlencoded 
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

我只是使用 file 协议运行我的网页。

例如:file:///E:/Mahendra/Practice%20Example/Test/OauthTest.html

我不确定这是否会导致问题。

【问题讨论】:

标签: javascript jquery ajax request-headers


【解决方案1】:

我通常会添加这样的标题(代码来自“使用 Sharepoint 中的 Web 代理查询远程服务”,here):

    $.ajax({
    url: "../_api/SP.WebProxy.invoke",
    type: "POST",
    data: JSON.stringify(
        {
            "requestInfo": {
                "__metadata": { "type": "SP.WebRequestInfo" },
                "Url": url,
                "Method": "GET",
                "Headers": {
                    "results": [{
                        "__metadata": { "type": "SP.KeyValue" },
                        "Key": "Accept",
                        "Value": "application/json;odata=verbose",
                        "ValueType": "Edm.String"
                    }]
                }
            }
        }),
    headers: {
        "Accept": "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "Authorization": "yourkeyvalueforauthorizationEXAMPLE",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: successHandler,
    error: errorHandler
});

告诉我进展如何

【讨论】:

  • 我试过了,但没有成功。可能是我使用file:/// 协议运行它,这会导致问题吗?
  • @mahendrakawde 我不确定你的意思,你应该编辑你的问题,以防你认为有任何进一步的信息可能导致问题。
  • @mahendrakawde file:/// 协议不起作用。你甚至需要在某个地方托管它localhost
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多