重定向时出现机架 CORS 错误
Rack-CORS error on Redirection
我遇到了一个问题,即在 Rails 4.1.0 上使用 rack-cors 0.2.9 作为我的 API 不允许跨源请求。我正在使用Angularjs作为前端来向此Rails应用程序添加记录。Chrome 显示此错误:
XMLHttpRequest cannot load http://localhost:3000/passages. The request
was redirected to 'http://localhost:3000/passages/67', which is
disallowed for cross-origin requests that require preflight.
我想我想我知道为什么会发生这种情况。这是我在控制器中的"创建"操作:
def create
@passage = Passage.new(passage_params)
respond_to do |format|
if @passage.save
format.html { redirect_to @passage, notice: 'Passage was successfully created.' }
format.json { render :show, status: :created, location: @passage }
else
format.html { render :new }
format.json { render json: @passage.errors, status: :unprocessable_entity }
end
end
end
请注意,保存段落后,我将被重定向到创建的特定段落记录的"显示"操作。显然,正是这种重定向触发了XHR错误。
我的问题是如何在我的 Rails 控制器中配置响应以避免此错误。如果我不重定向,我该怎么办?
感谢
更新:我没有提到尽管有错误,但确实创建了新记录。
更新:在阅读 Rails 4 文档时,我了解到可以简单地用浏览器的标头进行响应。请参阅导轨文档
但是,现在我在控制台中收到一个POST http://localhost:3000/passages 406 (Not Acceptable)
错误。研究此状态代码似乎表明我的 rails 应用程序没有向我的应用程序返回可接受的响应。我正在努力确定什么样的回应是可以接受的。有人有什么想法吗?
在阅读了另一篇 Stackoverflow 帖子的答案后想通了这一点。
这是我更新的控制器代码。请注意前面的代码注释掉:
def create
@passage = Passage.new(passage_params)
respond_to do |format|
if @passage.save
format.html do
head 200, content_type: "text/plain"
end
format.json { render json: @passage.to_json }
# format.html { redirect_to @passage, notice: 'Passage was successfully created.' }
# format.json { render :show, status: :created, location: @passage }
else
format.html { render :new }
format.json { render json: @passage.errors, status: :unprocessable_entity }
end
end
end
相关文章:
- 与域在同一台计算机上运行的NODEJS服务器的CORS错误
- XMLHttpRequest在$.ajax工作的地方给出了CORS错误
- 在Polymer中使用核心ajax时出现CORS错误
- 在 AngularJS 和 CodeIgniter3 中开机自检数据时出现 CORS 错误
- AngularJS应用程序中的CORS错误
- Meteor:使用HTTP.get从客户端访问网站(CORS错误)
- Catching'阻止加载混合活动内容'CORS错误
- ajax请求出现CORS错误
- 加载模板时出现AngularJS、Localhost和CORS错误
- 谷歌加 CORS 错误
- 同一域上的 CORS 错误
- 使用 elasticsearch.js 时出现 CORS 错误
- 护照节点.js CORS 错误
- 简单请求中的 Cors 错误:请求标头字段 预检响应中的访问控制-允许-标头不允许授权
- Firefox 和 chrome 的 CORS 错误
- 重定向时出现机架 CORS 错误
- 从localhost使用谷歌联系人api创建联系人时出现CORS错误
- Facebook oEmbed端点CORS错误
- 在Angular中使用解析客户端密钥会导致CORS错误
- 从文件//scheme运行的应用程序出现CORS错误