简体   繁体   中英

Unpredictable Access-Control-Allow-Origin behavior

I have a Rails app with the following action:

def some_action

  headers['Access-Control-Allow-Origin'] = 'http://www.example.com'
  headers['Access-Control-Request-Method'] = 'GET'
  headers['Access-Control-Max-Age'] = '1728000'

  n = Model.getNumber
  render :json => {:count => n}
end

I have some jQuery on example.com that does a $.getJSON on that action. Strangely, the behavior is completely unpredictable. Running those GET requests every few seconds, about 50% of them fail with the dreaded "Origin http://www.example.com is not allowed by Access-Control-Allow-Origin" message.

I really would have expected it to either work 100% of the time or fail 100% of the time. Why would it behave differently across multiple requests, seconds apart from the same browser?

Edit: I am caching that action... not sure if that makes any difference.

It sounds like an caching issue to me. If you are using an HTML cache it might be dropping the headers or if you are caching the data in your code make sure the headers get added regardless.

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