It's impossible to do local development due to the error message saying: "The requested resource does not have an 'Access-Control-Allow-Origin' header"

As a newcomer to AngularJS, I am currently working on my first app. I have set up a backend Restful service in another system that cannot be modified. Here is the code for my service:

var MainService = angular.module('MainService', [])
MainService.factory('MainData', ['$http', function ($http) {
    var urlBase = 'http://demoint:1234/rest.oms/basvc/barest';
    var MainData = {};
    MainData.getData = function () {
        return $http.get(urlBase + '/0/usecases?generation=true&UseCase=0.0.3550d.a6000015');
    };
    console.log(MainData);
    return MainData;
}]);

However, when I try to access the data, I encounter the following error message in my browser: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. https://i.sstatic.net/rzA18.png

I have tried different solutions to bypass this issue without success:

  1. Adding the following option to Chrome (startup parameter): --disable-web-security
  2. Installing this extension: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
  3. Adding the configuration code below to my main app:

    .config(['$httpProvider', function ($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            $httpProvider.defaults.withCredentials = true;
            delete $httpProvider.defaults.headers.common["X-Requested-With"];
            $httpProvider.defaults.headers.common["Accept"] = "application/json";
            $httpProvider.defaults.headers.common["Content-Type"] = "application/json";
        }
    ]);
    

Any suggestions on how to resolve this issue would be greatly appreciated.

https://i.sstatic.net/gFNEe.png

Thank you in advance! Fabio

Answer №1

JavaScript alone cannot give itself permission to access another website. This issue can only be resolved by enabling CORS on the backend server. If you just need to run this in your browser, you can turn off web-security in Chrome. To do this, close all instances of Chrome and run

chrome.exe --disable-web-security
.

For those using Chrome 49 or later, refer to this link for instructions: Chrome 49 plus --disable-web-security

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

Encountering the "Component resolution failed" error in Vue 3 when using global components

When I declare my Vue components in the top level HTML file, everything works fine. Here is an example: <body> <div class='app' id='app'> <header-bar id='headerBar'></header-bar> ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

What could be the reason behind this AngularJS todo application evaluating an if statement only once?

When using the function $scope.addTodo(), I encountered a strange behavior in my browser. It seems that the if statement is only evaluated on the first entry into the $scope.todos array. Upon creating a single todo, I am able to add blank todos even though ...

Is it possible to switch from a dropdown menu to radio buttons?

I am looking to change the dropdown menu in my search section into radio buttons. Currently, when I select something from the dropdown menu, the search fields are altered. Here is the code for the dropdown menu: <select id="qs_category" name="qs_catego ...

When an object is created, what is the most effective way to manage the asynchronous setup of one of its properties?

This is my first attempt at creating a JavaScript module/library, so I'm feeling a bit out of my depth. I apologize for not knowing exactly what to search for. My goal is to develop a library that stores information from a user-provided URL. The func ...

Provide the user with an .ics file for easy access

Recently, I developed an HTML5 application that enables users to download calendar entries in iCal format. These iCals are generated using PHP. Up until now, my method involved creating the iCal file with PHP and saving it to the web server's hard dis ...

Enable content to be displayed when hovering over it with a mouse in

As a newcomer to JavaScript, I am eager to learn how to add an interactive feature to my menu item. I want to create an info box that pops up when the menu item is clicked, and can also be displayed when hovering over it. Below is the script I have so far, ...

Failure encountered when attempting to load JSON data into datalist

I've been trying to incorporate inputs into a datalist in two different ways. However, I've encountered an issue with the first method not working properly. --> Check it out on bootlply var dataList = document.getElementById('json-datal ...

Is it possible to convert the pixel Array from canvas.getImageData() into base64 encoding?

After using a base 64 encoder on my canvas.getImageData() pixel array, I am trying to save the image to a file using its base64 encoded string. Unfortunately, I cannot use canvas.toDataURL because it is not supported in webOS. Below is the code I have wr ...

Updating Mapped Components with Selected State

One of the components in my project is a mapped component that dynamically displays API data. Each card displayed by this component receives unique props, resulting in cards that look different from one another. An example can be seen below. View Example ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Vue.js and Firestore will only update variables that do not have empty string values

Modify the variables that are not empty strings const state = reactive({ birthNumber: '', phoneNumber: '', DoctorName: '', DoctorPhone: '', }) db.collection(state.user.uid).doc( ...

What are the steps for creating personalized sliders with WordPress?

Seeking guidance on how to code WP Template files to enable control from the WP dashboard for adding or removing slider images. A sample code snippet is provided below. <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indi ...

Executing a function in a different script in AngularJS

My issue can be summarized as follows: Suppose I have a script called loadMe.js that contains a simple function returning an array. CallMe = function(){ return [1,2,3]; } Is there a way in ng to create another script that loads the loadMe.js script, then ...

The resolution of deferred actions is not as successful as foreseen

In my code, I have a method that queries documentdb for a specific document and returns the results to the caller. fetch: function(query) { var fetchDeferred = q.defer(); client.queryDocuments(collectionLink, query).toArray(function(err, docs) { ...

Generate an array containing all N-digit numbers with a sum of digits equal to S

I encountered a problem with my code translation process. Despite finding solutions in other languages, when I converted them to javascript, the expected array was not created. const find_digits = (n, sum, out, index) => { if (index > n || sum & ...

Exploring the efficacy of unit testing on Express controllers

After days of working on this, I've hit a wall and finally decided to ask for assistance. Everything runs smoothly when the server is up and API calls are made. However, when attempting to unit test the controller, I encounter some issues. I'm ...

Attempting to implement a unique filter on an ng-repeat that was crafted with creativity

In my current project on Ionic, I have been working on creating a screen that resembles a gallery. It consists of rows with three items in each row. The content is retrieved from a backend, so the code needs to dynamically scale as more items are fetched. ...

Troubleshooting Cross-Origin Resource Sharing (CORS) problem in Jquery

When using AJAX post from jQuery to call two REST services on different domains for business logic, a CORS issue arises. By setting crossDomain: true in my AJAX call following Google references, it works fine without specifying headers. However, if I inc ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...