微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax jquery跨域调用不发送授权头

在使用服务堆栈进行跨域调用的服务器之前,我已成功通过身份验证并获取我的令牌.

现在我想做另外一个调用来检索数据:

$.ajax({
    beforeSend: function(xhr) {                  
        xhr.setRequestHeader('Authorization','Basic ' + getToken());   
    },type: "GET",url: requestUrl,xhrFields: {
        withCredentials: true
    },async: true,dataType: 'json',crossDomain: true
})

当我看到我的谷歌chrome开发工具控制台我看到这样:

OPTIONS http://MyPc.company:82//customers 404 (Not Found) 
OPTIONS http://MyPc.company:82//customers Invalid HTTP status code 404 

XMLHttpRequest cannot load http://MyPc.company:82//customers. 
Invalid HTTP status code 404 (index):1

当我看着提琴手,我看到这个要求:

检查员=>认证:没有授权标题.

检查员=>生的:

OPTIONS http://MyPc.company:82//customers HTTP/1.1
Host: MyPc.company:82
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: GET
Origin: http://MyPc.company
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/30.0.1599.101 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin,accept,access-control-allow-headers,authorization,access-control-allow-methods,content-type
Accept: */*
Referer: http://MyPc.company/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

为什么不发送授权头?这似乎首先看到我的起因问题.

在JavaScript中
jQuery.support.cors = true;

   function make_base_auth(user,password) {
      var tok = user + ':' + password;
      var hash = btoa(tok);
      return "Basic " + hash;
  }
   function Dotest() {
          var TestRequest = new Object();
          TestRequest.name = "Harry Potter";             
          TestRequest.Id = 33;
         var username = "admin";
         var password = "test"; 
      $.ajax({
          type: 'Post',contentType: 'application/json',cache: false,async: false,url: serverIP + '/TestAPI/'+ TestRequest.Id,data: JSON.stringify(TestRequest),dataType: "json",beforeSend: function (xhr) {                    
           xhr.setRequestHeader("Authorization",make_base_auth(username,password));
          },success: function (response,status,xhr) {
              var s= response.message;      
          },error: function (xhr,err) {
              alert(xhr.statusText);
          }
      });
  }

应该为CORS启用服务配置

Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));

也许我以前的answer可以帮你.

或者更好的以下博客文章Community Resources

CORS BasicAuth on ServiceStack with custom authentication

原文地址:https://www.jb51.cc/ajax/160078.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐