ActionController ::使用GET重定向时的InvalidCrossOriginRequest

时间:2017-03-17 20:04:41

标签: ruby-on-rails

我正在尝试构建一个索引页面,其中一个窗体显示在一个模态中。在使用POST操作作为JS提交表单后,触发#create响应redirect_to操作#index的操作也作为JS,就像这样

def create
  @output = Output.new(output_params)

  respond_to do |format|
    if @output.save
      format.html { redirect_to @output, notice: 'Output was successfully created.' }
      format.json { render :show, status: :created, location: @output }
      format.js { redirect_to production_line_path @output.machine.production_line, machine_id: @output.machine_id, format: :js }
    else
      format.html { render :new }
      format.json { render json: @output.errors, status: :unprocessable_entity }
    end
  end
end

我的问题是,这给出了以下描述的错误

安全警告:另一个网站上的嵌入式<script>标记请求受保护的JavaScript。如果您知道自己在做什么,请继续并禁用此操作的伪造保护,以允许跨源JavaScript嵌入。

在35毫秒内完成422个不可处理的实体(浏览次数:27.2ms | ActiveRecord:1.5ms)

ActionController :: InvalidCrossOriginRequest(安全警告:另一个站点上的嵌入式<script>标记请求受保护的JavaScript。如果您知道自己在做什么,请继续禁用此操作的伪造保护以允许跨源JavaScript嵌入):

我不确定我是否试图以错误的方式做到这一点。我是否必须将JS的响应更改为不重定向,而是使用相同的控制器操作#create进行渲染?

2 个答案:

答案 0 :(得分:1)

您可以使用内置的redirect_to并将其传递给路径和参数,也可以使用JS重定向。如果你想重定向,请执行以下操作:

render js: "window.location.pathname = #{production_line_path @output.machine.production_line, machine_id: @output.machine_id}"

答案 1 :(得分:0)

我想我发现InvalidCrossOriginRequest错误的原因是什么。错误地,我的表单是作为JS请求发送而没有令牌,通常由UJS Rails适配器自动添加,但如果使用它。

我的表单缺少remote: true,而是包含format: :js,这让我觉得我正在使用UJS Rails适配器,并且我的POST请求带有CSRF保护所需的令牌。更多Cross-Site Request Forgery (CSRF)