Rack-CORS error on redirect

I am having an issue where cross origin requests are not allowed with rack-cors 0.2.9 on Rails 4.1.0 as my API. I am using Angularjs as the front end to add a post to this Rails app. Chrome showed this error:

XMLHttpRequest cannot load http://localhost:3000/passages. The request
was redirected to 'http://localhost:3000/passages/67', which is
disallowed for cross-origin requests that require preflight.

      

I think I understood why this is happening. Here is my "create" action in my controller:

def create
    @passage = Passage.new(passage_params)
    respond_to do |format|
      if @passage.save
        format.html { redirect_to @passage, notice: 'Passage was successfully created.' }
        format.json { render :show, status: :created, location: @passage }
      else
        format.html { render :new }
        format.json { render json: @passage.errors, status: :unprocessable_entity }
      end
    end
  end

      

Note that once the pass is saved, I am redirected to the "show" action of the particular pass entry. Apparently it is this redirect that is causing the XHR error.

My question is how to set up a response in my Rails controller to avoid this error. If I am not redirecting, what should I do?

thank

UPDATE: I didn't mention that a new record is actually being created despite the error.

UPDATE: While reading the Rails 4 documentation, I learned that one can simply respond with headers to the browser. See rail documentation

However, I am now getting an error POST http://localhost:3000/passages 406 (Not Acceptable)

in the console. Examination of this status code indicates that my rails application is not returning an acceptable response to my application. I am struggling to determine which answer would be acceptable. Does anyone have any idea?

+3


source to share


1 answer


Found it out after reading the answer from this other fooobar.com/questions/2178498 / ... post.

Here is my updated controller code. Note that the previous code is commented out:



def create
@passage = Passage.new(passage_params)

respond_to do |format|
  if @passage.save
    format.html do
      head 200, content_type: "text/plain"
    end
    format.json { render json: @passage.to_json }

    # format.html { redirect_to @passage, notice: 'Passage was successfully created.' }
    # format.json { render :show, status: :created, location: @passage }
  else
    format.html { render :new }
    format.json { render json: @passage.errors, status: :unprocessable_entity }
  end
end
end

      

0


source







All Articles