javascript - 使用 jQuery/ajax 的基本身份验证

标签 javascript jquery ajax request-headers

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

  1. 用户名
  2. 密码
  3. 资助类型

在提交表单时,我只想以 JSON 格式在我的 HTML 上显示服务器返回的响应。 我对 Web 服务的 AJAX 调用也需要设置 Authorization header 。 但不知何故标题没有得到设置。我在努力

 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();
    });

});

为什么不在我的代码中设置 header 。 请指正。

在网络选项卡的控制台(谷歌浏览器)中,我可以看到下面的请求 header

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

控制台中出现以下错误。 enter image description here

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

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

我只是使用文件协议(protocol)运行我的网页。

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

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

最佳答案

我通常这样添加 header (代码来自“使用 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
});

让我知道进展如何

关于javascript - 使用 jQuery/ajax 的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943042/

相关文章:

php - 在 Cakephp 中通过 ajax 发送数据

javascript - Google Maps API Infowindow 在提交前将 lat 和 lng 值输入到表单隐藏字段中

javascript - 使纹理的宽度适应其内容

php - jQuery动态类添加

javascript - 多个元素上的 jQuery 插件异步执行

javascript - 如何将 Rx.Observable.fromEvent 添加到 ajax 内容

javascript - 带有携带功能的变异数组?

javascript - while 在 javascript 中一遍又一遍地循环

jquery - 使用jquery val()及其innerhtml设置html select

javascript - 哪种ajax响应方式更好?