The requested resource is missing the 'Access-Control-Allow-Origin' header for the XMLHttpRequest

After extensive research on StackOverflow, I have not been able to find a solution to my specific issue among the several questions addressing similar errors.

The scenario involves running an Angular app (port 9000) and a Rails app (port 3000) on a remote server. The Angular app makes post requests to the Rails app.

Upon sending a request, the Javascript console displays the following error message:

XMLHttpRequest cannot load http://0.0.0.0:3000/api/query. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.241.16.159:9000' is therefore not allowed access. 

Based on my understanding, I need to modify something in my Rails app to enable connections from other servers (even though both are on the same ec2 instance).

I attempted to add a line like

  skip_before_filter :verify_authenticity_token

To one of my controllers in Rails, but it did not resolve the issue.

What steps should I take to fix this error?

Answer №1

Within the application_controller.rb file:

Ahead of filtering: add_allow_credentials_headers

def integrate_allow_credentials_headers                                                                                                                                                                                                                                                 
  # For more detailed information, visit https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#section_5                                                                                                                                                                                                   
  #                                                                                                                                                                                                                                                                                       
  # To enable the front-end to submit cookies for API authentication via 'withCredentials' in the XMLHttpRequest, certain headers must be included to prevent browser rejection of the response                                                                                                                                                                                                                                             
  response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'                                                                                                                                                                                                     
  response.headers['Access-Control-Allow-Credentials'] = 'true'                                                                                                                                                                                                                          
end 

def choices                                                                                                                                                                                                                                                                              
  head :status => 200, :'Access-Control-Allow-Headers' => 'accept, content-type'                                                                                                                                                                                                         

In the routes.rb configuration file:

Match any route to 'application#options', using [:options] as the method

Note that OPTIONS requests are being handled here due to Angular front-end performing POST requests. The inclusion of Access-Control-Allow-Credentials is specifically tailored for my app's cookie transmission from the front-end.

I recommend thoroughly reading through the mozilla link provided in the code above for a comprehensive understanding of CORS. Depending on your requirements, you may need to adjust the permissiveness of the code snippet above.

Answer №2

If you're not familiar with the issue at hand, let me explain what's going on...

Your apps are facing an obstacle known as the CORS policy

--

CORS (Corss Origin Resource Sharing)

When your application tries to access a endpoint on another server using XHR (XML HTTP REQUEST), it automatically blocks access to the requested resource by default.

The main reason for this restriction is to control which data/resources can be accessed through XHR, typically used for APIs.

--

rack-CORS

To resolve this issue, you must enable access to your Java application within your Rails app - I suggest utilizing the rack-CORS gem:

#Gemfile
gem 'rack-cors'

#config/application.rb
config.middleware.use Rack::Cors do
   allow do
     origins '*'
     resource 'api/jquery', :headers => :any, :methods => [:get, :post]
   end
end

This configuration will permit requests from various applications, resolving the CORS issue.

Answer №3

Give this code a try

  <httpProtocol>
          <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
           <add name="Access-Control-Allow-Headers" value="Content-Type" />
           <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
          </customHeaders>
     </httpProtocol>

within the <system.webServer> 

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

Transmit the canvas image and anticipate the AJAX POST response

I need to send canvas content to my API endpoint using ajax and wait for the response before moving on to the next function. Here is my current sending function: function sendPicture(){ var video = document.getElementById('video'); var canvas ...

Problem encountered while attempting to sort a table with JavaScript and jQuery

Having trouble sorting my table by the content in the first column. I've tried implementing code similar to the one found in this ANSWER, but unfortunately, it's not working as expected for me. When you run the snippet, you can see that the table ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

Guide to creating an asynchronous function

Starting my first react website and needing assistance with writing an asynchronous JavaScript function. I am currently working on uploading user input files to firebase storage and then making a post request to the API in order to store the data in the da ...

What is the best way to remove an item from an object?

I have a checkbox that adds its id value to an array when checked, and I want to remove this value when it is unchecked. I attempted to remove the id using indexOf() + splice(), but I am unable to use indexOf() because I am dealing with an object. Does a ...

How to incorporate a routing file within another routing file in Node.js

I have structured my routes as follows: / /business /business/stuff1 /business/stuff2 /business/admin For /business, I am using a separate file for the routing and functions. And similarly, for /business/admin, I also want to use a separate file f ...

What is the best way to maintain the previous input value on page refresh in Vuejs?

In my development project, I am utilizing the Laravel and Vue.js technologies. I am facing an issue where I need to set the input value to its previous old value when either refreshing the page or navigating back to it in a Vue dynamic component. Here is ...

Is it possible to optimize the Dojo build system to only compile Dojo when necessary?

Greetings. I've been assigned the challenging task of enhancing the efficiency of the Javascript build process in our application. The current setup involves using Dojo libraries and build system, which takes approximately 6 minutes for a complete bui ...

What are some possible reasons why ng-class in AngularJS might add a class instead of removing it?

I've encountered an issue in a project I am currently working on involving ng-class. When adding multiple conditions, the classes sometimes append instead of being removed based on the condition. For example: <div ng-app ng-controller="LoginCont ...

When trying to insert glyphicons into a textarea, the result is displaying the actual text instead

When the glyphicon is clicked, I want the entered content to be added dynamically to the textarea. $(document).ready(function(){ //Click Event of glyphicon class $(document).on('click','.glyphicon',function(){ ...

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

Angular JS does not acknowledge null values

Within my controller, the variable $scope.test is assigned a value from the server. When this value is null, line 1 of the code below prints 'null', however it still enters the else condition. I have attempted to use $scope.test != null and $scop ...

What is the best way to use a CSS class in my script specifically for specific screen sizes?

Utilizing bootstrap 4, my code is executing a for loop to generate eight divs with the class "item". To display five items per row, I am using the class "col-2". However, this results in six items being shown in a single row. Since I cannot include the o ...

What is the best way to adjust the autoplay volume to a set level?

I have a page with an audio element that autoplays, but I want to ensure the volume is set to a specific level in case a user has their volume turned up to 100%. Any suggestions on how to accomplish this? Here's the HTML code: <audio autoplay> ...

Reordering div elements with JQuery

As soon as my page loads, I have a div set to display:block and another div set to display:none. I have implemented a toggle switch that should replace the visible div with the hidden one. However, I am facing an issue where after performing the switch, ...

Tips for extracting specific values from JavaScript using jQuery in ASP to be utilized in the C# code behind section

I want to extract the selected values from a multiselect jQuery and use them in the code behind in C#. The script sources can be found at the following link: https://github.com/nobleclem/jQuery-MultiSelect Below is the ASP code I am using: <div class ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

The DOM assigned a new source to an image

Currently, I am working on a project that involves both jquery and PHP. In this project, users are able to upload images which are then displayed in blocks. The uploading functionality is already working, but I am facing an issue with setting the image sou ...

Transforming a JavaScript map into an array of objects

Given a map of key value pairs that I cannot control, I am tasked with converting them into an array of objects in a specific format. let paramArray1 = []; let paramArray2 = []; paramArray1.push({username:"test"}) paramArray1.pu ...