Tips for correctly implementing CORS (Cross-Origin Resource Sharing)

Is there a way to securely access a resource from a third-party domain using XML HTTP Requests (XHR, AJAX)?

I have set up CORS on both the target and origin sides with the following configuration:

Access-Control-Allow-Origin: http://www.example.com, https://www.example.com, http://www.example.org, https://www.example.org
Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS

However, browsers like Chrome, Firefox, and Internet Explorer are blocking the XHR request to when initiated from http://www.example.com/bar.

The most detailed error message is provided by Firefox:

XMLHttpRequest cannot load . The 'Access-Control-Allow-Origin' header contains multiple values 'http://www.example.com, https://www.example.com, , ', but only one is allowed. Origin 'http://www.example.com' is therefore not allowed access.

This error seems quite perplexing, almost like being told "Hey, you're A and want to talk to B, but B only accepts A and B. So sorry, no communication allowed." How can we correctly implement CORS (Access-Control-Allow-Origin) in this scenario?

Answer №1

Access-Control-Allow-Origin will only accept either * or a single origin.

If you wish to allow multiple origins while restricting some, you need to:

  1. Examine the the Origin request header
  2. Verify if it is included in your approved list of origins
  3. Add it to the Access-Control-Allow-Origin response header

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

Sending a parameter as text from .NET code-behind to a JavaScript function

So here's the situation: I have a gridview that is displayed in a new window separate from the parent window. This gridview contains multiple records, each with a "view" button that allows users to see more details about the record within the same new ...

encountered net::ERR_EMPTY_RESPONSE while attempting to locate a CSS file within an AngularJS directive

Every time my webpage attempts to access the css file from a directive, I encounter a net::ERR_EMPTY_RESPONSE. I have implemented door3's on-demand css feature, which allows for lazy loading of css files only when necessary. This feature works flawle ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Issue encountered while submitting a Laravel form: The error MethodNotAllowedHttpException in RouteCollection.php line 218 occurred. What is the possible cause of this error?

Within my view, there is a form that, upon submission, sends data to an ajax script. The goal is for this script to call the specified controllers in the post routes outlined in routes.php. These controllers should then handle the data and return the res ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

What is the best way to send additional data with getServerSideProps() in Next.js?

Not sure if this is a silly question, but I am currently working with a Django API and attempting to implement pagination on the search page using Next.js. As a newbie to Next.js, I have scoured the web for a solution but haven't found anything helpfu ...

Check the File Format (not just the Extension) prior to Uploading

When uploading a file within an HTML form, you can validate the extension using JQuery's Validation plugin: <form enctype="multipart/form-data" id="form-id"> <input type="file" name="file-id" id="file-id" /> </form> To validate ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

Dilemma of interdependencies between Socket.io and requirejs

I am facing a challenge with my legacy express project that has two servers. The project includes two separate client files: requirejs.config({ baseUrl: '/js' , paths: { "jquery": "lib/jquery/jquery-2.1.1.min", "socket.io" : "lib/socket/ ...

access the ckeditor within the frame

I have a CKEditor in a frame and am experiencing an issue. When I try to console log from the browser, it won't work until I inspect near the frame and perform the console log again. [This is the CKEditor] https://i.stack.imgur.com/fWGzj.png The q ...

When the state changes, initiate the animation

Currently, I am working with Vue.js and need to animate a navigation menu. My goal is to display two li elements when a user hovers over one of the navigation buttons. At the moment, I have set the data type showActivities to false by default and changed ...

Prevent parent element from changing color when child element is clicked

Check out my HTML: .imageURL:active .image_submit_div { background-color: #ccc; } .image_submit_div:active { background-color: #e6e6e6; } <div class="image_div"> <label for="id_image" class="image_submit_div"> <h3>+ add ...

"Exploring the best way to retrieve the angular filter value within a Node.js environment

Currently, I am facing an issue with accessing the value in Node.js using req.body when it is stored in ng-model. The ng-model includes an AngularJS filter, and I need to retrieve this filtered value from the input field in Node.js through req.body. Below ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Successfully resolving the API without encountering any response errors, even after sending a response

Once the data is successfully saved in the database and the image upload is completed, I am attempting to send res.json. However, I keep encountering the error message API resolved without sending a response for /api/auth/registeration, this may result in ...

Parent and router-outlet in Angular 4 fashion

Suppose we are presented with the following code: <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> <app-sidebar></app-sidebar> </div> <div class="c ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

Picture is currently not showing up in the division

I am currently working on an HTML page and I'm having trouble displaying an image within a division element. Below is the code snippet I tried: Here is the JavaScript part of my code: var filename = "andrew.png"; $("#detected").show().html('< ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...