0

I am trying to send a post request to my rails api using angular js post request but I am getting this error :

 XMLHttpRequest cannot load http://localhost:3000/api/v1/dis_generics. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 404.

I am trying to find a way how to send a post request using angular to rails api . My controller in rails is like this :

         class DisGenericsController < ApplicationController
          before_action :set_dis_generic, only: [:show, :edit, :update, :destroy]
        skip_before_action :verify_authenticity_token
          # GET /dis_generics
          # GET /dis_generics.json
          def index
            # @dis_generics = DisGeneric.all
           respond_to do |format|
               format.html
               format.json { render json: DisGenericDatatable.new(view_context) }
             end
          end

          # GET /dis_generics/1
          # GET /dis_generics/1.json
          def show
          end

          # GET /dis_generics/new
          def new
            @dis_generic = DisGeneric.new
          end

          # GET /dis_generics/1/edit
          def edit
          end

          # POST /dis_generics
          # POST /dis_generics.json
          def create
            @dis_generic = DisGeneric.new(dis_generic_params)

            respond_to do |format|
              if @dis_generic.save
                format.html { redirect_to @dis_generic, notice: 'Dis generic was successfully created.' }
                format.json { render :show, status: :created, location: @dis_generic }
              else
                format.html { render :new }
                format.json { render json: @dis_generic.errors, status: :unprocessable_entity }
              end
            end
          end

          # PATCH/PUT /dis_generics/1
          # PATCH/PUT /dis_generics/1.json
          def update
            respond_to do |format|
              if @dis_generic.update(dis_generic_params)
                format.html { redirect_to @dis_generic, notice: 'Dis generic was successfully updated.' }
                format.json { render :show, status: :ok, location: @dis_generic }
              else
                format.html { render :edit }
                format.json { render json: @dis_generic.errors, status: :unprocessable_entity }
              end
            end
          end

          # DELETE /dis_generics/1
          # DELETE /dis_generics/1.json
          def destroy
            @dis_generic.destroy
            respond_to do |format|
              format.html { redirect_to dis_generics_url, notice: 'Dis generic was successfully destroyed.' }
              format.json { head :no_content }
            end
          end

          private
            # Use callbacks to share common setup or constraints between actions.
            def set_dis_generic
              @dis_generic = DisGeneric.find(params[:id])
            end

            # Never trust parameters from the scary internet, only allow the white list through.
            def dis_generic_params
              params.require(:dis_generic).permit(:name, :is_combination, :rxcui, :status_id, :food_id, :hepatic_id, :renal_imp_id, :release_status_id, :is_essential)
            end
        end

and this is my angular request :

  var req = {
 method: 'POST',
 url: 'http://localhost:3000/api/v1/dis_generics',
 headers: {
    "Content-Type": "application/json"
 },
 data: {}
}
$http(req).success(function(data, status, header, config) {

alert( "failure message: " + JSON.stringify({data: data})); });

This is my application controller :

        class ApplicationController < ActionController::Base
        # Prevent CSRF attacks by raising an exception.
        # For APIs, you may want to use :null_session instead.
        include StaticPagesHelper
        skip_before_filter :verify_authenticity_token
           before_filter  :cors_preflight_check
     after_filter :cors_set_access_control_headers
       protect_from_forgery unless: -> { request.format.json? }

       def cors_set_access_control_headers
         headers['Access-Control-Allow-Origin'] = '*'
         headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
         headers['Access-Control-Allow-Headers'] = '*'
         headers['Access-Control-Max-Age'] = "1728000"
       end

       # If this is a preflight OPTIONS request, then short-circuit the
       # request, return only the necessary headers and return an empty
       # text/plain.

       def cors_preflight_check
         if request.method == :options
           headers['Access-Control-Allow-Origin'] = '*'
           headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
           headers['Access-Control-Allow-Headers'] = '*'
           headers['Access-Control-Max-Age'] = '1728000'
           render :text => '', :content_type => 'text/plain'
         end
       end
      end
Nilay Singh
  • 2,201
  • 6
  • 31
  • 61

1 Answers1

1

You need to add access-control header in your rails app OR you can just change the method to 'JSONP' as per this thread: AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

var req = {
 method: 'JSONP',
 url: 'http://localhost:3000/api/v1/dis_generics',
 headers: {
    "Content-Type": "application/json"
 },
 data: {}
}
$http(req).success(function(data, status, header, config) {
Community
  • 1
  • 1
johan
  • 998
  • 6
  • 20
  • Ok you can't, then your only other option is adding CORS in rails: http://stackoverflow.com/questions/17858178/allow-anything-through-cors-policy – johan May 19 '16 at 11:20