8

I'm attempting to access a web service with Prototype/AJAX and am running into an error I can't figure out: it seems that when I make a request to a server my request is interpreted as an OPTIONS rather than a GET request (and in turn throws a 501 - not implemented error since the server only allows GET requests, based on what I understand from Access-Control-Request-Method:). Am I missing something in my AJAX/request formulation that may be causing this error? I've read a bit into CORS/preflighted requests here but I'm unsure how it could apply when my code looks compliant...

Here's the relevant AJAX request:

function fetchMetar() {
var station_id = $("station_input").value;

    new Ajax.Request(REQUEST_ADDRESS, {
        method: "get",
        parameters: {stationString: station_id},
        onSuccess: displayMetar,
        onFailure: function() {
            $("errors").update("an error occurred");
        }
    });
}

and here's the error and relevant request info I get from Chrome:

Request URL:http://weather.aero/dataserver_current/httpparam?
 dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3
 &mostRecent=true&stationString=&stationString=KSBA
Request Method:OPTIONS
Status Code:501 Not Implemented
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, x-prototype-version, x-requested-with, accept
Access-Control-Request-Method:GET
Connection:keep-alive
Host:weather.aero
Origin:http://domain.com
Referer:http://domain.com/.../...html

What could I be overlooking here? Why does Chrome say the request is being sent as OPTIONS rather than GET? When Chrome spits out the Access-Control-Request-Headers: information, are these exclusively the only headers allowed in the request?

Thanks!

4

4 回答 4

15

花费太多时间寻找对原型的正确修复......最后,我们在伟大的 kourge (Wilson Lee) 文章中有一个非侵入性的解决方案!这是一段摘录:

大多数主要的 Ajax 框架都喜欢在您实例化的 Ajax 请求上设置自定义 HTTP 标头;最流行的标头是 X-Requested-With: XMLHttpRequest。因此,您的请求被提升为预检请求并失败。如果您的请求是跨域请求,则修复是防止您的 JavaScript 框架设置这些自定义标头。如果您的 URL 被认为是远程的,jQuery 已经通过不设置自定义标头巧妙地避免了无意的预检请求。如果您使用其他框架,则必须手动阻止这种情况。

它可以很简单:

new Ajax.Request('http://www.external-domain.net/my_api.php?getParameterKey=getParameterValue', {
            method:'post',
            contentType:"application/x-www-form-urlencoded",
            postBody:'key=' + value,
            onSuccess: function(response) {
                // process response
            },
            onCreate: function(response) { // here comes the fix
                var t = response.transport; 
                t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { 
                    if (/^(accept|accept-language|content-language)$/i.test(k)) 
                        return original(k, v); 
                    if (/^content-type$/i.test(k) && 
                        /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) 
                        return original(k, v); 
                    return; 
                }); 
            } 
        });

如果您发现此解决方案有任何缺点/改进,我们欢迎您分享 :)

于 2013-03-08T17:39:57.350 回答
6

实际上它是preflight request,因为 Prototype 在请求中添加了自定义标头X-Requested-With, X-Prototype-Version。由于这些标头浏览器发送第一个OPTIONS请求。XHR 规范说:

对于使用 HTTP GET 方法的非同源请求,当设置了 Accept 和 Accept-Language 以外的标头时,会发出预检请求。

如何解决这个问题呢?我只能看到尽快解决这个问题的一种可能性:完全覆盖方法Ajax.Request#setRequestHeaders(),例如在 Prototype.js 之后插入这个脚本:

Ajax.Request.prototype.setRequestHeaders = function() {
  var headers = {
    // These two custom headers cause preflight request:
    //'X-Requested-With': 'XMLHttpRequest',
    //'X-Prototype-Version': Prototype.Version,
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  };

  if (this.method == 'post') {
    headers['Content-Type'] = this.options.contentType +
      (this.options.encoding ? '; charset=' + this.options.encoding : '');

    /* Force "Connection: close" for older Mozilla browsers to work
     * around a bug where XMLHttpRequest sends an incorrect
     * Content-length header. See Mozilla Bugzilla #246651.
     */
    if (this.transport.overrideMimeType &&
        (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
          headers['Connection'] = 'close';
  }

  if (typeof this.options.requestHeaders == 'object') {
    var extras = this.options.requestHeaders;

    if (Object.isFunction(extras.push))
      for (var i = 0, length = extras.length; i < length; i += 2)
        headers[extras[i]] = extras[i+1];
    else
      $H(extras).each(function(pair) { headers[pair.key] = pair.value; });
  }

  for (var name in headers)
    this.transport.setRequestHeader(name, headers[name]);
}

此补丁从任何 AJAX 请求中删除自定义标头。如果您仍然需要这些标头用于非 CORS 请求,则可能会添加更多逻辑,这将有可能在选项中禁用这些标头new Ajax.Request()(我将在此处跳过此变体以缩短答案)。

于 2012-12-11T19:24:20.980 回答
1

实际上,使用 Prototype.js V1.7 更容易:

Ajax.Responders.register({
    onCreate:function(r){
        r.options.requestHeaders={
        'X-Prototype-Version':null,
        'X-Requested-With':null
        };
    }
});

如果其值为 null,Prototype.js 会丢弃任何预定义的标头。

于 2015-09-02T10:48:18.673 回答
0

我从来没有使用过 Prototype,我不确定我会有多少用处。但是我快速浏览了文档,并没有看到对方法和参数的任何支持。

所以试试:

new Ajax.Request(REQUEST_ADDRESS+"?stationString="+station_id, {
    onSuccess: displayMetar,
    onFailure: function() {
        $("errors").update("an error occurred");
    }
});

此外,我刚刚注意到您示例中的 stationString 应该在引号中,假设它不是变量。

于 2012-12-11T06:29:16.950 回答