我有一个Rails 5 API,在/ client目录下运行一个React前端。我试图通过React前端实现资源的所有CRUD操作。 的阵营前端在端口3000上运行,和Rails API后端是我已经安装/启用on Rails的CORS端口3001上运行:React前端POST/PUTS到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…}
但是当我使用邮差提交下列PUT到http://localhost:3000/dogs/1,它成功地更新狗!我究竟做错了什么?
{
"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中间件设置中设置了“origin”*“',它会起作用吗?或者可能添加“127.0.0.1:3000”。在您停止服务器以重新加载更改后,务必运行'spring stop'。 – treiff
不幸的是我仍然收到一个错误的请求。 – Hinchy