John Davidson

javascript - CORS error: Response to preflight request The 'Access-Control-Allow-Origin' header contains multiple values '*, *',

0 comments
Message:


I am creating an angularjs UI CMS and using php for the backend connection. On the php script I have added the following headers:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");


On the angularjs side, I am using $ajax to call the APIs in each controller, using the following code:


$.ajax({type : 'GET', url : 'https://.../get_city_tokens.php?city_token=' + $location.search().id, contentType: 'application/json; charset=utf-8',dataType: 'json' ,success: function(response) {console.log(response)}});


The error I receive is the following:


Access to XMLHttpRequest at 'https://worldcitytrail.com/WCT_online/get_city_tokens.php?city_token=YYf727XkGL2L8CeX' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values ', ', but only one is allowed.


I have searched the angular.js project in order to find where the "" header is in other files, however I see that I haven't set anywhere else these headers.


Could please anyone help?



My Answer:
It looks like the issue is with the multiple values in the 'Access-Control-Allow-Origin' header. Instead of setting it to '*', you can try setting it to the specific origin that you are making the request from.

You can update your PHP script to include the specific origin in the header like this:

php
header("Access-Control-Allow-Origin: http://localhost");
header("Content-Type: application/json; charset=UTF-8");


This way, you are specifying the exact origin that is allowed to make requests to your PHP script.

Additionally, you can also try using the $http service provided by AngularJS instead of using $.ajax. Here is an example:

javascript
$http.get('https://.../get_city_tokens.php?city_token=' + $location.search().id)
.then(function(response) {
console.log(response.data);
});


Using $http service will handle CORS headers automatically and might help resolve the issue.

Make sure to replace 'http://localhost' with the actual origin of your AngularJS application.

Rate this post

3 of 5 based on 5709 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us