【问题标题】:Access-Control-Allow-Origin error sending a jQuery Post发送 jQuery Post 的 Access-Control-Allow-Origin 错误
【发布时间】:2013-01-23 23:09:45
【问题描述】:

我阅读了很多关于“Access-Control-Allow-Origin”问题的论坛。大多数论坛要求使用 dataType:'jsonp',但通常 jsonp 会命中 GET 请求,我想做 POST 请求。最终 GET 请求也不起作用。

实际上我将 iPhone 应用程序转换为 PhoneGap,因此将 Objective-c 代码重写为 HTML-5 和 Jquery 移动。我试图点击的 url 在 Objective-c 中效果很好。

这里是objective-c代码

NSString *username=[self urlEncodeValue:[userNameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *password=[self urlEncodeValue:[passWordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *params = [[NSString alloc] initWithFormat:@"username=%@&password=%@",username,password];

NSData *paramData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[params release];
NSString *paramsLength = [NSString stringWithFormat:@"%d", [paramData length]];

NSString *urlString=[[NSString alloc] initWithFormat:@"%@?",[dict valueForKey:@"LoginAuthentication"]];

NSURL *authURL = [NSURL URLWithString:urlString];
[urlString release]; 

NSHTTPURLResponse *authenticationResponse= nil; 
NSMutableURLRequest *authenticationRequest = [NSMutableURLRequest requestWithURL:authURL];
[authenticationRequest setHTTPMethod:@"POST"];
[authenticationRequest setValue:paramsLength forHTTPHeaderField:@"Content-Length"];
[authenticationRequest setHTTPBody:paramData];
NSError *error = nil;
int errorCode;

NSData *responseData = [NSURLConnection sendSynchronousRequest:authenticationRequest  
          returningResponse:&authenticationResponse 
             error:&error]; 

if ([authenticationResponse respondsToSelector:@selector(allHeaderFields)]) {
    //success
}

上面的代码效果很好。

这是我转换为 javascript 的代码,它给出“Access-Control-Allow-Origin”错误

$(document).ready( function() {
    $.ajax({
        type: "POST",
        crossDomain: true,
        //dataType:'jsonp',
        //callback: '?',
        url : "https://externalserver.com/loginAuth?", 
            data : {'username' : 'username', 'password' : 'password'},
        success : function (response) {
            alert('login failed');
        }, 
        error: function(e){
            console.log(e);              
        }
    });
});

我尝试了 GET/POST 请求,并尝试在某个本地服务器上运行此本地文件。没有任何效果。

我收到以下错误消息

XMLHttpRequest 无法加载 https://externalserver.com/loginAuth?。 Access-Control-Allow-Origin 不允许 Origin null。

XMLHttpRequest 无法加载https://externalserver.com/loginAuth?。 Access-Control-Allow-Origin 不允许 Origin null。

【问题讨论】:

  • 你把网址加入白名单了吗?
  • 是的,我已将 URL 添加到白名单中。顺便说一句,我在浏览器中遇到了这个错误。
  • 当您在浏览器中收到此错误时,您是通过服务器访问您的网页还是直接从您的计算机打开 html 文件?
  • @Romain 如果我尝试使用本地服务器,它会给出“Origin localhost:8080 is not allowed by Access-Control-Allow-Origin.”而是空访问错误

标签: jquery cordova jquery-mobile


【解决方案1】:

PhoneGap 应用程序被视为移动应用程序,而不是浏览器,因此可以跨域。您需要更改您的 服务器 代码以添加此标头

Access-Control-Allow-Origin: *

这将允许发送 PhoneGap 请求的 null 来源。这应该适用于 GET 和 POST 请求,而无需使用 JSONP。

【讨论】:

    【解决方案2】:

    浏览器不允许您从另一个域请求资源(图像和脚本文件是该规则的明显例外)。

    这可以通过几种方式解决。

    1. 第一种方法是使用 JSONP 调用(跨域访问的当前标准),是的,JSONP 只允许 GET。但这只是解决方案的一部分。服务器端也需要改成允许跨域调用。

      为了能够从 javascript 访问外部资源。远程资源必须在响应头中包含 access-control-allow-origin。如果您可以控制该资源,则需要将此响应标头添加到 * (或您的域,如果您想要更受限制的访问控制)。当然,这部分解决方案将取决于您的服务器端架构(PHP、ASP.NET、JSP ...)

      这里有一个PHP/jQuery解决方案详细描述:http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

      还必须将返回结果包装到 jsonpCallback 函数中,所以返回应该看起来像这样:

      someFunction("{...}");
      

      someFunction 是回调函数的名称,经典的 JSON 是 {....}。可以看到,它是用 someFunction(.

      包裹的

      jQuery 端应该是这样的:

      $.ajax({url: server_url,
          type: "GET",       
          data: save_data,
          dataType: "jsonp",
          jsonpCallback: 'successCallback',
          async: true,
          beforeSend: function() {
      
          },
          complete: function() {
      
          },
          success: function (result) {
      
          },
          error: function (request,error) {
      
          }, 
          successCallback:function(){
      
          }
      });
      

      http://devlog.info/2010/03/10/cross-domain-ajax/

    2. 或代理解决方案。我不会写它,因为我从未测试过它。仅当您无权访问服务器端代码时才使用此解决方案:

      http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html http://developer.yahoo.com/javascript/howto-proxy.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 2018-03-16
      • 2013-05-08
      • 2012-05-08
      • 2018-12-12
      • 2014-03-18
      • 2017-06-15
      相关资源
      最近更新 更多