Rails跨域资源共享:ActionController :: RoutingError(没有路由匹配[OPTIONS]“/batches”)

3

我想在Rails中执行跨平台请求。

我的jQuery代码如下:

<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>

我的控制如下所示:-
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

但每次我尝试使用表单添加记录时,Rails日志中都会显示以下错误:

当我提交第一条数据时出现错误。

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"):

当我提交多次数据时出现错误:-

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

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

有人能帮我解决这个问题吗?

1个回答

5
你需要配置Rails以支持CORS。
其中一种解决方案是使用rack-cors gem。
以下代码片段需要添加到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

是的,它起作用了,但它引发了新问题...现在它显示ActionController :: InvalidAuthenticityToken(ActionController :: InvalidAuthenticityToken): - Shital luitel
你需要确保正确传递真实性令牌。查看此链接:https://dev59.com/emw05IYBdhLWcg3wfx80 - Mihai Dinculescu
无法验证CSRF令牌的真实性。在16毫秒内完成了422个无法处理的实体(ActiveRecord:0.0毫秒)ActionController :: InvalidAuthenticityToken(ActionController :: InvalidAuthenticityToken): - Shital luitel
当我使用跨平台请求提交表单时,这就是提供的完整错误。 - Shital luitel
你想看我的表单吗? - Shital luitel
直接调试通过 Authenticity Token 的代码即可。我看到的一个问题是 $.ajaxSetup 应该在 $(document).ready 函数内部。 - Mihai Dinculescu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接