我遇到的问题是,在Rails 4.1.0作为我的API使用机架编号0.2.9不允许跨源请求。我使用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.
我想我弄清楚为什么会这样。这是我的#34;创建"控制器中的动作:
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
请注意,保存段落后,我会被重定向到" show"创建特定通道记录的动作。显然,正是这种重定向触发了XHR错误。
我的问题是如何在我的Rails控制器中配置响应,以避免此错误。如果我没有重定向,我该怎么办?
THX
更新:我没有提到新的记录确实是在错误的情况下创建的。
更新:在阅读Rails 4文档时,我了解到可以简单地使用标题响应浏览器。见the rails documentation
但是,现在我在控制台中收到POST http://localhost:3000/passages 406 (Not Acceptable)
错误。研究这个状态代码似乎表明我的rails应用程序没有返回对我的应用程序可接受的响应。我正在努力确定哪些回应是可以接受的。有人有什么想法吗?
答案 0 :(得分:0)
在阅读了其他{{3}}帖后的答案时想出来了。
这是我更新的控制器代码。请注意前面的代码已注释掉:
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