因此,在StackOverflow上有一些问题可以解决此错误,但是在我检查的10-15中,我找不到确切问题的解决方案。
我在远程服务器上运行Angular应用程序(端口9000)和Rails应用程序(端口3000)。angular应用程序通过发布请求将请求发送到rails应用程序。
发出请求时,Javascript控制台显示以下错误消息:
XMLHttpRequest cannot load http://0.0.0.0:3000/api/query. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.241.16.159:9000' is therefore not allowed access.
从阅读的内容来看,我需要更改我的Rails应用程序,以便它可以接受来自其他服务器的连接(这很奇怪,因为两个应用程序都在同一个ec2实例上运行)。
我尝试添加像
skip_before_filter :verify_authenticity_token
到我的控制器中,但这似乎没有任何效果。
如何解决此错误?
在app / controllers / application_controller.rb中:
before_filter :add_allow_credentials_headers
def add_allow_credentials_headers
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#section_5
#
# Because we want our front-end to send cookies to allow the API to be authenticated
# (using 'withCredentials' in the XMLHttpRequest), we need to add some headers so
# the browser will not reject the response
response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
end
def options
head :status => 200, :'Access-Control-Allow-Headers' => 'accept, content-type'
end
在config / routes.rb中:
match '*any' => 'application#options', :via => [:options]
注意,这是对Angular前端执行POST请求时需要的OPTIONS请求的响应。我对Access-Control-Allow-Credentials所做的工作是针对我的应用程序的,因此cookie是从前端发送的。
我强烈建议您阅读上面我的代码中该mozilla链接中的文档。它对CORS有非常详尽的解释。您可能会发现上面的代码对您的目的而言太宽松了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句