Today, I developing a web app using to AngularJs and REST API. The REST APIs are hosted on some different servers. When I calling to this REST APIs that time I facing this issues[CORS (Cross Origin Request Sharing)] and solved this issue now using the below stuff.
In the below example we set the $httpProvider.defaults.useXDomain = true; that means the AJAX request send with X-Requested-With and Removing the necessary header, so the server is not rejecting the all incoming request.
In AngularJs version > 1.2, No need to any other extra work. Simply you add stuff in the app config file.
The code sample as given below.
In the below example we set the $httpProvider.defaults.useXDomain = true; that means the AJAX request send with X-Requested-With and Removing the necessary header, so the server is not rejecting the all incoming request.
In AngularJs version > 1.2, No need to any other extra work. Simply you add stuff in the app config file.
The code sample as given below.
var app = angular.module( 'corsApp' , []); app.config([ '$httpProvider' , function ($httpProvider) { $httpProvider.defaults.useXDomain = true ; delete $httpProvider.defaults.headers.common[ 'X-Requested-With' ]; } ]); |
var app = angular.module('corsApp', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
If
above solution is not worked in your applications then you can try to add the
header request and response like below solutions. i.e.
//Configue to http provider.
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete
$httpProvider.defaults.headers.common['X-Requested-With'];
}]);
The "Access-Control-Allow-Origin" is use to set the response from server, not on client request to allow clients from different origins to have access to the response.
// Added all header request and response.
// Added all header request and response.
app.all('/*', function (request, response,
next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.header("Access-Control-Allow-Methods", "GET,
POST",
"PUT",
"DELETE");
next();
});
References,
References,
http://stackoverflow.com/questions/23823010/how-to-enable-cors-in-angularjs
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
https://gist.github.com/mlynch/be92735ce4c547bd45f6
http://stackoverflow.com/questions/29915657/solved-enable-cors-angularjs-to-send-http-post-request
http://stackoverflow.com/questions/29915657/solved-enable-cors-angularjs-to-send-http-post-request
I hope you are enjoying with this post! Please share with you friends. Thank you!!