简体   繁体   中英

How to get response headers authorization in jquery ajax success?

I'm setting encrypted username and password authorization in fron end and getting request header response bearer authorization from server. In ajax i'm getting to get that response header in safari correctly but in chrome and firefox its like a null. The problem only in chrome and firefox to get bearer token. How to fix that issues?

Ajax code,

$.ajax({
            type:"POST",
            url:url,
            dataType: "json",
            async:false,
            headers:{ 
                'Authorization':'Basic '+btoa(useremail+":"+password)
            },
            data:'{"datas"}',
            success: function (data, status, request, xhr){
                alert(request.getResponseHeader('Authorization'));
            }

在此输入图像描述

Note that as of jQuery 1.8 async option is deprecated.

As to why this probably happens:

During a CORS request, the getResponseHeader() method can only access simple response headers. Simple response headers are defined as follows:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

And as for the solution:

If you want clients to be able to access other headers, you have to use the Access-Control-Expose-Headers header. The value of this header is a comma-delimited list of response headers you want to expose to the client.

Source: https://www.html5rocks.com/en/tutorials/cors/

With reference from this articel : http://osric.com/chris/accidental-developer/2014/08/using-getresponseheader-with-jquerys-ajax-method/

Try with done function as shown in the example in the article :

$.ajax({
    type:"POST",
    url:url,
    dataType: "json",
    async:false,
    headers:{ 
        'Authorization':'Basic '+btoa(useremail+":"+password)
    },
    data:'{"datas"}',
}).done(function (data, textStatus, xhr) { 
    console.log(xhr.getResponseHeader('Authorization')); 
});

try this..

    var settings = {
    "crossDomain": true,
    "url": url,
    "method": "POST",
    "headers": {
     "content-type": "application/x-www-form-urlencoded",
     "Authorization":"Basic "+btoa(useremail+":"+password)
    },
   "data": {
   "name": "name"
  }
 }

    $.ajax(settings).done(function (data,status, xhr) {
     console.log("Authorization=> "+xhr.getResponseHeader('Authorization'));
 });    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM