Javascript 重定向时出现机架CORS错误
我在Rails 4.1.0上的rack cors 0.2.9作为我的API时遇到了一个跨源请求被禁止的问题。我使用Angularjs作为前端,向这个Rails应用程序添加一条记录。Chrome显示此错误:Javascript 重定向时出现机架CORS错误,javascript,ruby-on-rails,angularjs,redirect,Javascript,Ruby On Rails,Angularjs,Redirect,我在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 f
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控制器中配置响应以避免此错误。如果我不重定向,我该怎么办
Thx
更新:我没有提到,尽管有错误,新记录确实被创建了
更新:在阅读Rails 4文档时,我了解到可以简单地用标题响应浏览器。看
然而,现在我得到了一个
帖子http://localhost:3000/passages 406(不可接受)
控制台中出现错误。研究此状态代码似乎表明我的rails应用程序没有向我的应用程序返回可接受的响应。我正在努力确定什么样的回应是可以接受的。有人有什么想法吗?在阅读了另一篇文章的答案后,我明白了这一点
这是我更新的控制器代码。请注意,前面的代码已注释掉:
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