What are the steps to creating a basic CORS request?

THE SCENARIO:

I'm currently developing an AngularJs app that requires making a CORS request to fetch data from an api on a different domain.

The api I'm working with outputs a simple json structure for testing purposes:

[{"id":0,"name":"First"},{"id":1,"name":"Second"},{"id":2,"name":"Third"}]

My goal is to retrieve this data and display it within my app.

$HTTP CALL ISSUE:

When making the $http call, I encountered the following error related to the api being on a different domain:

No 'Access-Control-Allow-Origin' header is present on the requested resource

CORS REQUEST - THE IMPLEMENTATION:

// Function to create the XHR object.
$scope.createCORSRequest = function(method, url)
{
    var xhr = new XMLHttpRequest();

    if ("withCredentials" in xhr) 
    {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } 
    else if (typeof XDomainRequest != "undefined") 
    {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } 
    else 
    {
        // CORS not supported.
        xhr = null;
    }

    return xhr;
}

// Helper method to parse the title tag from the response.
$scope.getTitle = function(text)
{
    return text.match('<title>(.*)?</title>')[1];
}

// Perform the actual CORS request.
$scope.makeCorsRequest = function()
{
    var url = 'http://DOMAIN.COM/main/json_export_test';

    var xhr = $scope.createCORSRequest('GET', url);

    console.log('----- xhr -----');
    console.log(xhr);

    if (!xhr) 
    {
        alert('CORS not supported');
        return;
    }

    // Response handlers.
    xhr.onload = function() 
    {
        var text = xhr.responseText;
        var title = $scope.getTitle(text);
        alert('Response from CORS request to ' + url + ': ' + title);
    };

    xhr.onerror = function() 
    {
        alert('Oops, there was an error making the request.');
    };

    xhr.send();
}

Upon running the makeCorsRequest function, the xhr.onerror alert is triggered, but I am unsure of the reason behind this issue.

THE API FUNCTIONALITY:

Below is the simple php function used within the api for testing purposes:

public function json_export_test()
{
    $data = array(
        array(
            "id" => 0,
            "name" => "First"
        ),
        array(
            "id" => 1,
            "name" => "Second"
        ),
        array(
            "id" => 2,
            "name" => "Third"
        )
    );

    echo json_encode($data);
}

THE QUERY:

How can I successfully execute a CORS request?

EDIT - THE RESOLUTION:

Following the proposed solution, here's how the api code looks after modification:

public function json_export_test()
{
    header('Access-Control-Allow-Origin: *');

    $data = array(
        array(
            "id" => 0,
            "name" => "First"
        ),
        array(
            "id" => 1,
            "name" => "Second"
        ),
        array(
            "id" => 2,
            "name" => "Third"
        )
    );

    echo json_encode($data);
}

Answer №1

Basically: To send a request with XMLHttpRequest, just make the usual call and let the browser take care of the rest. (Except for outdated browsers that may not support CORS or require the use of XDomainRequest instead of XMLHttpRequest — but it seems like you already know about this).

The error message you're seeing indicates that there's no CORS response, so your JavaScript doesn't have permission to access data from the other site.

To solve this, you need to add Access-Control-Allow-Origin: * (or a more specific value) in the HTTP response to fulfill the cross-origin request.

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

Randomizing the JSON loop on every page refresh

Having a JSON file containing various data items (as an example) that I am utilizing with handlebars.js to generate templates. The challenge lies in displaying 15 stories (each within their own div) on page load while shuffling their positions upon each r ...

Having issues with setInterval function when restricting the number of MySQL rows

My simple chat application with setInterval is experiencing an issue when I try to limit the number of rows displayed from the database. Currently, the chat loads everything from if($q == "load") { and functions correctly. However, when I attempt ...

Event triggered when a Socket.IO connection is disconnected

Everything seems to be working well with my code when a new user joins, but I'm encountering issues when a user leaves as it doesn't display anything. Can someone point out the error in my code? Below is my server-side code: const express = requ ...

Do the two types of updater functions for setState in React hold the same value?

Recently, I came across the concept of using updater functions for setState in React. After learning about this, I noticed it being implemented in two different ways. Imagine having a state object structured like this: interface State { readonly expand ...

Enhancing an existing Express project with socket.io (plus a side of React)

I have been working on a project with Express, which includes a messaging system. Initially, everything was functional with POST/GET methods for sending and receiving messages. However, I wanted to implement real-time messaging by integrating socket.io on ...

Setting the default value in setState in React Native allows you to initialize state

const fetchData = async (key) => { try { const jsonData = await AsyncStorage.getItem(key) return jsonData != null ? JSON.parse(jsonData) : false; } catch(error) { console.log(error); } } useEffect ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

Node.js with ejs supports the inclusion of partials, but sometimes struggles to locate the variable that has been defined in the partial file

This is the code that should be included in the main ejs file: <% const IDP_URL = "http://idp.com:8082"; const SP_ID = "testing"; const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw=="; const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs"; const L ...

Populate a JSON table in React with checkboxes and automatically mark them based on the JSON data

I'm currently working on creating a React table using JSON data like this: [ { "Id_side": 123, "Name_side": "R4", "Name_cycle": "C1" }, { "Id_side": 345, "Name_side": "M1", "Name_cycle": "C2" ...

Tips for stopping the entire webpage from scrolling in Vuetify

Hey there, I'm facing an issue with scrolling on mobile devices and iPads. When I view my site on desktop, there is no scrolling behavior, but as soon as I switch to a mobile device or iPad, the scroll appears. This problem is specific to mobile devic ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

Three.js - Troubleshooting: Imported OBJ model displaying partially transparent triangles

Currently, I am encountering an issue with an obj file that was exported from Rhino3D into obj format. In this case, half of the triangles making up a certain part of the model appear to be transparent, despite appearing fine in the 3D editor. var loader ...

Issue with loading controllers in route files [Node.js]

I've encountered an issue while trying to include a user controller into my routes for a node js app. Everything was working fine until suddenly it started throwing an error message. I've thoroughly checked the code for any potential issues but s ...

I am interested in changing the sitecore search facet filter from allowing multiple selections to only allowing a single

I have successfully implemented the Sitecore search widget and the result list is working as expected. However, I encountered an issue with the filter functionality using facets. By default, it supports multiple filters but my requirement is to have singl ...

What is the best way to incorporate this locale variable into the primary script?

Is it possible to access the locale variable from the main script and convert it into a global variable? The current method I tried does not seem to be working. Any advice or guidance is appreciated. //Converting a local variable to a global variab ...

Adjusting the opacity of the background image in the section - focus solely on the background

This section is what I'm working on. <section ID="Cover"> <div id="searchEngine">hello</div> </section> I am trying to achieve a fade in/out effect specifically for the background image of the Cover section. T ...

Collect all chosen items within a form along with their concealed inputs in preparation for submission

Imagine a scenario where you have a table filled with polaroid pictures and you are tasked with deciding whether to keep or discard each one. Yes signifies keeping it, while No indicates throwing it away. I am looking to create an element for each photo t ...

Show Data on the Right-hand Side

Objective: Arrange the component names in two columns - left and right, with different objects like input textboxes based on a browser width of 981px. The desired layout is showcased in this link "https://jsfiddle.net/2w9kskr2/". Challenge: After impl ...

Having trouble seeing the output on the webpage after entering the information

I can't seem to figure out why the result is not displaying on the HTML page, so for now I have it set up as an alert. <h1>Factorial Problem</h1> <form name="frm1"> Enter any number :<input type="text" name="fact1"& ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...