问题描述
我有一个Rails-API,其中有带有rack-cors
gem的CORS设置。该API有一个帖子模型,我希望能够在其中发布帖子,就像基本的脚手架一样。它托管在Heroku上。
当我从我的React前端使用Axios
发出发布请求时,它会发送OPTIONS预检信息,但是此后,再也没有发出过POST请求。
但是,如果我发送带有空参数的请求,则请求过程将在选项和帖子发布后完全完成(尽管为空,但我对模型没有任何验证)。
我的cors配置:
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins '*'
resource '*',headers: :any,methods: [:get,:post,:put,:patch,:delete,:options,:head]
end
end
我来自React前端的axios请求。
return axios({
method: 'post',url: authHeader.getApiUrl() + '/api/v1/posts',params: data,headers: authHeader.getHeader()
})
at=info method=OPTIONS
path="/api/v1/posts?cover_image="image
url"&title=TItle&subtitle=The+Start+of+Something+New&tag=Tag&body=&specification=blog"
host=myapp.herokuapp.com request_id=cddc8ded-849a-44c5-b655-1af87d29a71d fwd="102.67.23.174"
dyno=web.1 connect=0ms service=1ms status=200 bytes=287 protocol=https
解决方法
我看到有人对此添加了书签,所以我将答案留作以后参考。
所以问题不是来自Rails,而是我在React中的表单提交处理。当我添加e.preventDefault()
时,请求继续进行,这是我第一次省略。
createPost = (e) => {
e.preventDefault()
this.setState({loading: true})
AdminServices.uploadPost(
this.state.coverImageLink,this.state.title,this.state.subtitle,this.state.tag,this.state.body,this.state.specification
).then(resp => {
this.switchTab("blog")
}).catch(error => {
if (error.response) {
console.log(error.response)
this.setState({
message: error.response.data.error,loading: false
})
} else if (error.request) {
this.setState({
message: "Please check your network",loading: false
})
} else {
console.log(error)
}
})
}