3

I am trying to perform cross-platform request in rails.

My jquery code is as follow:-

<script>
    $.ajaxSetup({
      headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      }
    });
    $(document).ready(function () {
        $('#submit-button').click(function() {
            $.ajax({
                type: "POST",
                url: "http://localhost:3000/batches",
                beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
                xhrFields: {
                    withCredentials: true
                },
                data: {     
                    batch: {
                      name: $("#name").val(),
                      course_id: $("#course_id").val(),
                      start_date: $("#start_date").val(),
                      end_date: $("#end_date").val(),
                      status: $("#batch_status").val(),
                      }
                },
                dataType: "JSON",
              error: function(error) {
                    console.log(error);
                      },
              success: function(data) {
                         console.log(data);
                         return false;
                      },
            })
        });
    })
</script>

And my control is as follow: -

def new
    @batch = Batch.new
    respond_to do |format|
      format.json
      format.html
    end
  end

  def create
    @batch = Batch.new(batch_param)
    respond_to do |format|
       if @batch.save
         format.json { render json: @batch, status: :created, location: @batch }
         format.html { redirect_to @batch, notice: "Save process completed!" }
       else
          format.html {
            flash.now[:notice]="Save proccess coudn't be completed!"
            render json: @batch.errors, status: :unprocessable_entity
          }
          format.json { render json: @batch.errors, status: :unprocessable_entity}
      end
    end
  end
def batch_param
      params.require(:batch).permit(:name, :course_id, :start_date, :end_date, :status)
    end

But each time when i try to add record using form it shows following error in rails log:-

Error when i submit my first data

Started OPTIONS "/batches" for 127.0.0.1 at 2017-01-11 22:02:49 +0545
  ActiveRecord::SchemaMigration Load (0.5ms)  SELECT "schema_migrations".* FROM "schema_migrations"

ActionController::RoutingError (No route matches [OPTIONS] "/batches"):

Error when i submit data more the one time: -

Started OPTIONS "/batches" for 127.0.0.1 at 2017-01-11 22:08:50 +0545

ActionController::RoutingError (No route matches [OPTIONS] "/batches"):

Can anyone help me in this problem.

Squashman
  • 13,649
  • 5
  • 27
  • 36
Shital luitel
  • 135
  • 15

1 Answers1

5

You need to configure Rails to support CORS.

One solution is to use the rack-cors gem.

The following snipped will be needed to be added to config/application.rb

module YourApp
  class Application < Rails::Application

    # ...

    # Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

    # Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

  end
end
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
  • Yeah it worked but it gave raise to new problem... now it says ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): – Shital luitel Jan 11 '17 at 16:47
  • You need to make sure that you're properly passing around the authenticity token. Check this: http://stackoverflow.com/questions/7203304/warning-cant-verify-csrf-token-authenticity-rails – Mihai Dinculescu Jan 11 '17 at 16:50
  • Can't verify CSRF token authenticity. Completed 422 Unprocessable Entity in 16ms (ActiveRecord: 0.0ms) ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): – Shital luitel Jan 11 '17 at 16:54
  • This is the full error provided when i submit my form using cross-platform request.... – Shital luitel Jan 11 '17 at 16:55
  • Do you want to see my form? – Shital luitel Jan 11 '17 at 16:57
  • Just go ahead and debug the code that passes Authenticity Token. One thing that I'm seeing is that the `$.ajaxSetup` should be inside the `$(document).ready` function. – Mihai Dinculescu Jan 11 '17 at 16:58