我正在嘗試構建一個 React - Rails API 專案。我添加gem 'rack-cors'并創建了config/initializers/cors.rb檔案:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:3001"
# The React part will be on port 3001 so thats way we add it
# Change it to the production url when going on production
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
我只想允許該埠3001,因為那是我的 React 前端將服務的埠。現在我想測驗這是否真的有效并阻止其他請求。
到目前為止,我一直在使用Postman測驗 API(必須下載它才能使用http)。我認為因為我只將過濾器添加到特定埠,它會阻止來自的請求Postman但它仍然顯示 API 呼叫中請求的資料。
另外,如果我嘗試在瀏覽器上這樣訪問它:
http://localhost:3000/api/v1/users
它仍在提供資料,應該阻止每個埠,除了3001.
為什么會這樣?有沒有其他方法可以仔細檢查它是否有效?謝謝!
注意:我殺死了服務器并再次重新啟動它,它仍然表現相同
uj5u.com熱心網友回復:
從瀏覽器進行 API 呼叫(不是來自 URL,也不是來自郵遞員)。可以通過ajax來測驗。
Postman does not implement the CORS restrictions
uj5u.com熱心網友回復:
為了在本地測驗 CORS,我找到了這個 repo:https ://github.com/njgibbon/nicks-cors-test
只需克隆它,然后單擊該html檔案,它就會在您的瀏覽器中打開。默認情況下,它呼叫github API( https://api.github.com ) 并從那里獲取資訊。您可以打開控制臺并檢查它。如果將其更改為https://google.com它將引發 CORS 限制。
同樣,您可以將其更改為http://localhost:3000/api/v1/users(在我的情況下),它會在我現在擁有的配置中引發 CORS 錯誤。
要仔細檢查,只需轉到cors.rb并放置origins "*". 重新啟動應用服務器并嘗試再次運行 html 檔案。現在我們不會被阻止了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482379.html
