Error Message: Issue with Rack-CORS during Redirection

Encountering an issue with cross-origin requests being blocked using rack-cors 0.2.9 on Rails 4.1.0 for my API. Employing Angularjs as a front end to submit a new record to this Rails project results in the following error displayed by Chrome:

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.

The root cause of this problem seems to be related to the "create" action within the 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

After saving the passage, the redirection to the specific record's "show" action triggers the XHR error.

My query revolves around configuring the response in the Rails controller to prevent this error. If avoiding redirection, what alternative approach should I take?

Thank you

UPDATE: It should be noted that despite the error, the new record is successfully created.

UPDATE: After consulting the Rails 4 documentation, it appears possible to solely respond with headers to the browser. For reference, check out the rails documentation

However, I am now faced with a

POST http://localhost:3000/passages 406 (Not Acceptable)
error in the console. Further investigation into this status code suggests that my Rails app is not providing an acceptable response to my application. Any suggestions on what response would be considered acceptable?

Answer №1

Discovered the solution after finding help in a response from another Stackoverflow thread.

Below is the revised code snippet for my controller. Take note of the previous code that has been 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...

Achieving Equal Heights in Two Grid Sections using React MUI

How can I create two separate grids next to each other using MUI, both taking up 50% of a larger grid? In the image displayed below, I am struggling to make the heights of the two sections match. I want the smaller grid items (cards) to dynamically adjust ...

What could be the reason for Safari generating larger videos than Chrome when utilizing the MediaDevices.getUserMedia() API?

Embarking on a small experiment to gauge the size of captured videos using the MediaDevices.getUserMedia() API. My Safari implementation yielded videos 5-10 times larger than those in Chrome. Here's the code snippet: index.html: <html lang=" ...

Idea for a New Web Chat Feature

Hey there, I've been considering adding a shoutbox to my website. However, I'm looking for a solution that will seamlessly integrate with my existing members database. I have some ideas in mind but I'm not entirely sure of the best approach. ...

Perform an Ajax request in JavaScript from the server-side code

I am currently trying to call an Ajax javascript function from the codebehind in order to fetch data. To achieve this, I am using the following method: Page.ClientScript.RegisterStartupScript( GetType(), "MyKey", "Myfunction();", true); ...

Populate a text field with a selected value from a dropdown menu

How can I populate a text field with a value from the database when an option is selected from a combo box? Note: both the values in the combo box and the one I want to show in the text field are fetched from the same table in the database. ...

Locate the articles containing the array in question

I have tags stored in the database as a string of arrays, and I am trying to search for articles based on these arrays. Article.find_by(tags: 'xbox') Unfortunately, this is leading to an error. I then tried: Article.where(tags: 'xbox&apos ...

I have implemented checkbox input types on my page, and I have noticed that whenever I use the delete or retrieve methods, they work as intended

I have checkbox inputs in my Asp.Net MVC project where I use jQuery to get the IDs of selected items and send them to the controller via AJAX. The methods are functioning correctly, but the page does not reload automatically to display the results. I hav ...

What is the best approach to arranging three items within an array in a specific sequence?

This particular query is an extension of a previous one found here In my application, I have implemented a cart feature where users can add or remove items. When displaying this cart, it will only show a maximum of 3 items. However, the problem arises whe ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

What is the proper way to construct a URL with filter parameters in the RTK Query framework?

I am facing difficulty in constructing the URL to fetch filtered data. The backend REST API is developed using .Net. The format of the URL for filtering items is as follows: BASE_URL/ENDPOINT?Technologies=some-id&Complexities=0&Complexities=1& ...

Understanding AngularJS binding: Decoding the mystery of "<?" symbol

After spending more than 10 minutes trying to find the answer, I'm certain that others will benefit from this information as well. Can someone explain the meaning of '<?' in AngularJS databinding when used for a directive? ...

Error encountered in index.ejs due to Angular controller issue

In my index.ejs page, there is a slideMenu that inserts various HTML views within the index.ejs file. Each HTML view has its own controller, with each controller stored in its own .js file. All these scripts are included in the index.ejs file. However, th ...

Transfer information stored in a promise to the callback function of another controller

When Controller A sends a request via promise, what is the most effective method for running a callback function simultaneously in another Controller B? Is it best to broadcast via a service in the original callback and then listen for it in the other cont ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

concentrate on the input box

Once I click on the CPM, my goal is to automatically place the cursor in the centralized field of this page: . Despite my attempts to use different code snippets in the console, I have not been successful. I experimented with document.getElementById("se ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Showcasing the nested json data along with images in a table using plain javascript

I am looking to display nested JSON data containing images in an HTML table using vanilla JavaScript. I have tried different approaches but haven't been successful in achieving the desired result. You can find my code on Codepen. Here is the expected ...