即使存在Access-Control-Allow-Origin标头也拒绝XHR?

问题描述 投票:0回答:1

在用Rails 3编写的开发服务器上,我在应用程序控制器中设置了CORS标头以允许跨域访问:

class ApplicationController < ActionController::Base
  before_filter :cross_domain_setup
  # ...
  def options_request
    head :no_content
  end
  def cross_domain_setup
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, PUT, POST, DELETE, OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With"
  end
  # ...
end

# in routes.rb:
match "*path" => "application#options_request", constraints: { method: "OPTIONS" }

这是我的前端代码(Sencha Touch):

// note: this should probably be done using MVC, but my server doesn't
// have a RESTful API for this particular resource
var statusText = accepted ? "accepted" : "ignored";
Ext.Ajax.request({
    url: "http://localhost:3000/friends/requests",
    method: "PUT",
    params: {
        friend_request: {
            _id: friendRequest.internalId,
            status: statusText
        }
    },
    success: success,
    failure: failure
});

这将发送以下HTTP请求:

OPTIONS /friends/requests?_dc=1388320908671 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: PUT
Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Access-Control-Request-Headers: x-requested-with, content-type
Accept: */*
Referer: http://localhost/path/to/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

我的服务器回应:

HTTP/1.1 204 No Content
Date: Sun, 29 Dec 2013 12:41:48 GMT
Status: 204 No Content
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Requested-With
X-UA-Compatible: IE=Edge
Cache-Control: no-cache
Set-Cookie: blahblahblah; path=/; HttpOnly
X-Request-Id: 01157976a93af661045eefdf4b8beb2e
X-Runtime: 0.016029

看起来都正确。那么,如何在开发人员工具中得到以下错误?

XMLHttpRequest cannot load http://localhost:3000/friends/requests?_dc=1388320920825. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

并非所有请求都被阻止。我还没弄清楚为什么。

可能出什么问题了?

javascript ruby-on-rails xmlhttprequest sencha-touch
1个回答
0
投票

我认为正在发生的事情是所请求的资源正在产生500个内部服务器错误(无法将符号转换为整数等),但这显示为被阻止的请求,可能是因为未发送CORS标头由于500错误?

无论如何,使用rack-cors gem似乎已经解决了问题。现在我的前端收到了预期的500错误。

© www.soinside.com 2019 - 2024. All rights reserved.