我想從簡單的React.js應用程序中刪除用戶。我收到一個302錯誤,我的控制檯也顯示這個錯誤。React.js應用程序沒有'Access-Control-Allow-Origin'頭文件
Fetch API cannot load http://localhost:3001/ . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise)TypeError: Failed to fetch
我在客戶端刪除請求是這樣的:
export function deleteUser(id){
return fetch(`http://localhost:3000/api/v1/users/${id}`, {
method: 'DELETE'
}).then(res => res.json())
}
而且在頂層容器中的功能是這樣的:
handleDeleteUser(id){
localStorage.clear('token')
deleteUser(id)
.then((data) => this.setState({
current_user: data
}))
}
我遇到了很多關於CORS的答案。這是從服務器端我的application.rb中的文件:
module Our_gardenApi
class Application < Rails::Application
config.api_only = true
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :delete, :patch, :options]
end
end
end
end
我UsersController還試圖像這樣重定向:
def destroy
user = User.find(params[:id])
user.destroy
redirect_to "http://localhost:3001"
end
寶石「機架CORS」也就是我的Gemfile內安裝。
最終,用戶被成功刪除。我只是遇到了重定向問題。 任何幫助解釋將不勝感激!
嘗試閱讀CORS文檔https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – Nemani
你有沒有添加'rack-cors'寶石進入你的寶石文件 –
嘿@AshishJambhulkar。是的,我做到了。忘了提到這一點。謝謝! – peterchic