![](/img/trans.png)
[英]Angular $http to Web Api gives error of XMLHttpRequest -No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]XMLHttpRequest No 'Access-Control-Allow-Origin' header is present on the requested resource
所以StackOverflow上有一些問題可以解決這個錯誤,但在我檢查過的10-15個問題中,我無法找到解決我的確切問題的方法。
我在遠程服務器上運行Angular應用程序(端口9000)和Rails應用程序(端口3000)。 角度應用程序通過發布請求向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
我的控制器在rails中,但這似乎沒有任何影響。
我該如何解決這個錯誤?
在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]
注意,這是響應OPTIONS請求,如果Angular前端正在執行POST請求,您將需要這些請求。 我使用Access-Control-Allow-Credentials進行的操作是針對我的應用程序的,因此cookie是從前端發送的。
我強烈建議您在上面的代碼中閱讀該mozilla鏈接中的文檔。 它對CORS有一個非常徹底的解釋。 您可能會發現上面的代碼對您的目的來說過於寬松。
如果你還沒有讀過它,讓我告訴你一些問題是什么......
您的應用的CORS策略存在問題
-
CORS(Corss Origin資源共享)
當您使用XHR( XML HTTP REQUEST )訪問另一台服務器上的endpoint
時,您的應用程序(盡管我不確定如何)將默認拒絕訪問請求資源。
發生這種情況的原因是為了確保只通過XHR提供某些數據/資源,這就是為什么它主要用於API之類的原因。
-
機架CORS
無論如何,您需要允許訪問Rails應用程序中的Java應用程序 - 我個人會推薦使用rack-CORS
gem:
#Gemfile
gem 'rack-cors'
#config/application.rb
config.middleware.use Rack::Cors do
allow do
origins '*'
resource 'api/jquery', :headers => :any, :methods => [:get, :post]
end
end
這將“允許”來自您不同應用程序的請求,為您解決問題。
試試這個代碼
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
inside the <system.webServer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.