/clientディレクトリにあるReactフロントエンドを持つRails 5 APIがあります。私は、リアクションフロントエンドを介してリソースのCRUDアクションをすべて実装しようとしています。 ザ・が反応フロントエンドは、ポート3000上で実行されている、とRails APIバックエンドは、私がCORSは/ Railsの上で有効にインストールされているポート3001上で実行されている:リアクションフロントエンドPOST/PUTS to Rails 5 APIバックエンド
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:3001'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
をして反応package.jsonに私が持っている:
"proxy": "http://localhost:3000",
マイレールルートは以下のとおりです。
Prefix Verb URI Pattern Controller#Action
dogs GET /dogs(.:format) dogs#index
POST /dogs(.:format) dogs#create
dog GET /dogs/:id(.:format) dogs#show
PATCH /dogs/:id(.:format) dogs#update
PUT /dogs/:id(.:format) dogs#update
DELETE /dogs/:id(.:format) dogs#destroy
現在は、私が正常に取得して反応使って犬のリストを表示することができます。
window.fetch('dogs')
.then(response => response.json())
.then(json => this.setState({dogs: json}))
.catch(error => console.log(error))
}
しかし、私はそれぞれの犬を編集できるようにしたい。だから私が反応「犬」で、次の更新を処理するコンポーネントを持っている:
handleSubmit(event) {
event.preventDefault()
let url = `dogs/${this.state.id}`
let data = {
dog: {
id: this.state.id,
name: this.state.name,
age: this.state.age,
sex: this.state.sex,
description: this.state.description
}
}
let updateDog = {
method: 'PUT',
body: data
}
fetch(url, updateDog)
.then(json => console.log(json))
.catch(error => console.log(error))
}
私が提出したときに、Chromeのコンソールで を(しかし私はちょうど今のところそれをロギング、最終的に状態を設定するために応答を使用します)
PUT http://localhost:3000/dogs/1 400 (Bad Request)
Dog.jsx:61 Response {type: "cors", url: "http://localhost:3000/dogs/1", redirected: false, status: 400, ok: false…}
をしかし、私はhttp://localhost:3000/dogs/1に次のPUTを提出するポストマンを使用する場合、それが成功した犬を更新します。フォーム私は次のエラーを取得します!私は間違って何をしていますか?
{
"id": 1,
"name": "Lord Barkington",
"age": 7,
"sex": "M",
"description": "Pieces of Eight jolly boat mutiny me cable spike Sail ho ho draught reef sails grapple schooner topsail Yellow Jack.",
}
confitのミドルウェア設定で 'origins '*''を設定した場合、好奇心をそそられて動作しますか?あるいは '127.0.0.1:3000'を追加することもできます。また、サーバーを停止して変更をリロードした後で、必ず 'spring stop'を実行してください。 – treiff
残念ながら、私はまだ悪い要求を得ています。 – Hinchy