简体   繁体   English

Rails CORS:ActionController::RoutingError(没有路由匹配 [OPTIONS] "/batches"):

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

I am trying to perform cross-platform request in rails.我正在尝试在 Rails 中执行跨平台请求。

My jquery code is as follow:-我的 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>

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:-但是每次当我尝试使用表单添加记录时,它都会在 Rails 日志中显示以下错误:-

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.任何人都可以帮助我解决这个问题。

You need to configure Rails to support CORS .您需要配置 Rails 以支持CORS

One solution is to use the rack-cors gem.一种解决方案是使用rack-cors gem。

The following snipped will be needed to be added to config/application.rb需要将以下剪辑添加到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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RoutingError(没有匹配的路由[OPTIONS] - RoutingError (No route matches [OPTIONS] ActionController :: RoutingError(没有路由与[GET]匹配” / assets / javascripts - ActionController::RoutingError (No route matches [GET] "/assets/javascripts Ruby on Rails:PDF.JS ActionController :: RoutingError(没有路由与[GET]“ / pdf js / web / viewer.html”匹配): - Ruby on Rails: PDF.JS ActionController::RoutingError (No route matches [GET] “/pdf js/web/viewer.html”): ActionController :: RoutingError(没有路由与[GET]“ / javascripts / application.js”匹配) - ActionController::RoutingError (No route matches [GET] “/javascripts/application.js”) 如何从另一个Rails项目中调用JavaScript文件? ActionController :: RoutingError(没有路由与[GET]“ / assets / trackmetrics.js”匹配) - How do call a javascript file from another Rails project? ActionController::RoutingError (No route matches [GET] “/assets/trackmetrics.js”) 服务器上的Rails 6收到很多“ ActionController :: RoutingError:没有路由匹配[GET] /31194a065aebf1674b61.worker.js”的请求 - Rails 6 on server getting a lot of “ActionController::RoutingError: No route matches [GET] /31194a065aebf1674b61.worker.js” requests ActionController :: RoutingError Rails和Angular - ActionController::RoutingError Rails and Angular ActionController :: RoutingError(没有路由与[GET] controller_name / fusioncharts.widgets.js匹配 - ActionController::RoutingError (No route matches [GET] controller_name/fusioncharts.widgets.js 为什么我得到这个 ActionController::RoutingError (没有路由匹配 [GET] “/users/assets/application.js”) - Why I am getting this ActionController::RoutingError (No route matches [GET] “/users/assets/application.js”) 如何找到导致ActionController :: RoutingError的原因,没有路由匹配错误? - How can I find what is causing the ActionController::RoutingError No route matches error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM