Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid ActionController::InvalidCrossOriginRequest exception?

I updated my rails app to Rails 4.1 and started getting ActionController::InvalidCrossOriginRequest exception. I found bing bots actively crawl my dynamically generated javascript file.

I think it's correct that rails raises this exception since javascript is called directly, but my log is filled up with this exception.

Is there a way to avoid bots raising this exception without turning off csrf protection?

My Controller looks like this.

class ListsController < ApplicationController
  before_filter :authenticate_user!

  def add
    @list = List.find(params[:id])
    respond_to do |format|
      format.js { render 'add' }
      format.html { redirect_to list_path(@list) }
    end
  end

end
like image 722
kengo Avatar asked Apr 22 '14 03:04

kengo


1 Answers

To add to J-H's answer, and assuming you need some help with CORS, you should know that every host uses a CORS policy to determine who can (and can't) access their server directly

Your error is basically because your server's CORS policy is still defaulted to "denying" every direct XHR access. The way around this is to determine the endpoints on your server which will be available for external resources

It happens the best way to do this is to use the rack-cors gem, as recommended by J-H :)

like image 63
Richard Peck Avatar answered Oct 09 '22 07:10

Richard Peck