Is XMLHttpRequest able to enable CORS?

I have been struggling for hours to access a resource from a different domain. I came across information on that suggests using the XMLHttpRequest in a CORS-enabled browser should solve the issue. However, I keep encountering the error message "

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.nczonline.net/. This can be fixed by moving the resource to the same domain or enabling CORS.
"

Even though I am using Firefox 34 which is expected to support CORS according to http://caniuse.com/#feat=cors, the problem persists.

I'm attempting a basic example from

If you take a look at the code snippet below:

<script type="text/javascript">
    function log(msg){
        var output = $('#output');
        output.text(output.text() + " | " + msg);
        console.log(msg);
    }

    function createCORSRequest(method, url){
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr){
            xhr.open(method, url, true);

            log("'withCredentials' exist in xhr");
        } else if (typeof XDomainRequest != "undefined"){
            xhr = new XDomainRequest();
            xhr.open(method, url);

            log("XDomainRequest is being used");
        } else {
            xhr = null;

            log("xhr is null");
        }
        return xhr;
    }

    function main(){
        log("Attempting to make CORS request");

        var request = createCORSRequest("get", "https://www.nczonline.net/");
        if (request){
            request.onload = function(){
                log("LOADED!");
            };

            request.send();
        }
    }

    $(window).load(function(){
        main();
    });
</script>

In my tests, the following output was generated:

Attempting to make CORS request
'withCredentials' exist in xhr
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.nczonline.net/. This can be fixed by moving the resource to the same domain or enabling CORS.

Running the code on JSFiddle via https://jsfiddle.net/zf8ydb9v/ yielded the same results. Could there be another setting that needs to be adjusted besides using XMLHttpRequest for CORS to work properly?

Answer №1

The same origin policy is in place to protect your data security, not the server's: it prevents malicious scripts from accessing your information on other servers using your cookies. If you choose to, you can disable this policy at your own risk on your browser.

In Chrome/Chromium, you can disable the same origin policy by starting it with the --disable-web-security option:

chromium-browser --disable-web-security

However, if you want this functionality for your users, they will be unable to make CORS requests unless they have disabled this security feature in their browsers (which is generally not recommended except for testing).

Some servers may allow these types of requests intentionally if they believe it will benefit their users without harming them, using Access-control headers.

If you still wish to provide this functionality to users, creating a Chrome extension is an option, as extensions are not restricted by the same origin policy.

A common workaround is to handle cross-origin requests on the server side and return the results to your application. It is important to code this carefully to avoid introducing security risks to your server-side software. For example, in PHP, you could hard code the URL to fetch like this:

<?php
    echo file_get_contents("http://your_cross_request/");
?>

Then, making an ajax request to this page (from the same origin) will retrieve the content of the remote URL.

Answer №2

CORS policies are included in the response that is sent back by the server after receiving your request. If the webpage you requested does not contain these headers, it doesn't matter what actions you took on your end using a default browser; you will encounter a security issue.

The important CORS headers typically appear as follows, with the last one being crucial:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: example.com

I attempted to access the site "samplewebsite.com" and upon inspecting the response headers, I did not notice any of these headers present. This indicates that the server is not set up to allow loading in this manner.

If you have control over the website settings, it would be advisable to add the necessary headers to your responses, possibly specifying allowed origins instead of opting for a wildcard approach.

If you are simply testing your code and wish to experiment with a third-party integration, consider loading a page that does send these headers, such as example.com.

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

Unable to open Google Maps link within React application

I've set up a conditional link based on location, using the following code: <a href={`https://maps.google.com/maps?q=${delivery_branch.latitude},${delivery_branch.longitude}`} target={"_blank"} >{`${delivery_branch.street}, ${d ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Using Three.js to position objects along a curve and rotate them toward the center of a circle

I'm working on developing a sleek VR menu that presents menu items in a curved column below the camera as the user looks down. The challenge is to have the items rotated towards the camera while appearing uniform. Here's what I've come up w ...

Trouble with Mongoose: Data Not Being Saved

I'm encountering difficulties with a basic query on my database. While following this tutorial at https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4, the author receives a JSON object containing the name field (the only custom fi ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

Executing asynchronous functions that invoke other asynchronous functions

I'm facing an issue with executing a sequence of asynchronous functions inside an array. When I call the functions individually, it works perfectly as shown in the example below: function executeAll(string) { return new Promise(function (resolv ...

Mongoose - Error: Method 'findOne' is not callable

Having trouble integrating Facebook login with passport? Check out the error message below: TypeError: Cannot call method 'findOne' of undefined at Strategy._verify I made sure to include models.js in my app.js and passed it into the passport m ...

Modify the component's background color when hovering

Is there a way I can modify the background color of the entire panel on hover? I am currently using a simple bootstrap panel with bootstrap-react: <LinkWrapper url={url}> <Panel header="text" bsStyle="primary"> <p>text.</p> ...

Map markers in AngularJS NgMap are showing incorrect positions when specified by city name

Trying to implement a simple marker according to this example, but it only works with static city names like "Toronto". When using dynamic city names, the marker is placed in the center of the world map. Below is my code: <div map-lazy-load="https://m ...

Tips for showcasing success messages when submitting a form using ajax

Within my Rails 3.2 application, I am working on a form that is submitted using Ajax and provides user feedback through flash messages. There seem to be multiple approaches to tackle this issue. One option is to set up format js in the controller and the ...

Generate and send a form programatically using AJAX

One interesting feature on my website is the shoutbox with an edit link. When users click on this link, a prompt appears allowing them to edit their post. After submitting the edited post, a form is dynamically created and submitted to another page for pro ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

How can one retrieve the set-cookie value in a <meta http-equiv> tag using Node.js?

When working with Node.js, I am encountering a scenario where I need to detect instances of a cookie being set in a response so that I can make changes to it. There are two ways in which cookies are being set: Through the use of the set-cookie HTTP heade ...

Redirecting Firebase user authentication to a different webpage

I have developed a signupPage.html to validate a user and save information to the real-time database in Firebase with the following code: signUp_button.addEventListener('click', (e) => { var email = document.getElementById('email ...

Guide on implementing "Displaying 1 of N Records" using the dataTables.js framework

let userTable = $("#user_table").DataTable({ 'sDom': '<"row-drop"<"col-sm-12 row"lr>><"row"t><"row-pager"<"col-sm-12 col-md-5"i><"col-sm-12&qu ...

Safari on iOS 9 having trouble playing embedded YouTube videos

Recently, I discovered that my YouTube embedded videos are not playing on iOS devices when on my website unless you click in the top left corner of the video. Even after removing all extra YouTube parameters and using standard iFrame embed code, the issue ...

Navigating a vast code repository in Node.js

As I prepare to start a Node.js project with a sizable codebase, my aim is to keep my code isolated from the node_modules directory. I am keen on utilizing namespaces and organizing my code into folders for better management. However, it seems like I woul ...

The element within the array object is not properly defined and is causing error messages to be displayed

Whenever I try to use Icons[link.label] in my const, I receive the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'iconsProps'. No index sig ...

Comparing the Round-trip Time of AJAX versus Web Sockets

Can one expect a variance in round-trip time when using web sockets (message) versus a standard HTTP GET for sending information to the server and receiving a response? Assuming the web socket is already connected and DNS has been resolved. From my unders ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...