XMLHttpRequest cannot load https://myserver1:8281/myurl/ext. Preflight issue - angularjs

I know already the same question has been asked for the preflight issue and so many solutions are provided but i tried almost all of them but its not helping me.
I have a rest api written in java(Sprint) and calling it in my js. My service is getting called and its getting success. I my java code i have written the code for the redirection but direction is not happening and i am getting the below error in browser console:
XMLHttpRequest cannot load https://myserver1:8281/myurl/ext. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'https://myserver2:21242, *', but only one is allowed.
I tried adding 'Access-Control-Allow-Origin':'*' in the header but still facing the issue. Also tried adding the OPTIONS in the allowed methods in the header.
Below is my js code:
$scope.validateToken = function(){
var config = {
headers : {
'ContentType': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Expires': '-1',
'X-Requested-By': 'test'
},xhrFields: {
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,OPTIONS'
}
};
$http.get($scope.getUrl, {headers:{'token': $scope.ssoLinkData.token}}).success(function(data, status, headers, config){
}).error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
Below is my java code:
#GET
#Path("/ext")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response myMethod() {
return Response.seeOther(getLocation(redirectionUrl)).
header("Access-Control-Allow-Origin", "*").
header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS").
header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token").
status(200).build();
}
I added the header information in my java code after seeing some post related to the issue. But that is also not helping me.
Can some please help me on this? Thanks in advance

Have you tried doing this:
myApp.config(['$httpProvider', function ($httpProvider){
$httpProvider.defaults.headers.post = {}; //to override the $http post service, hence avoiding browsers encapsulation of post over OPTIONS
}]);
This overrides the default POST pre-flight request and adding "OPTIONS" to your API response header should solve this problem.

Related

CORS Issue in Web Console (angular js)

I have a developed a web console in angular JS in which I am using post and put methods and making HTTP requests in which I send json and calling a WSO2 REST API to get response accordingly. Its running on server but I am facing CORS problem. I have add add extension in browser and enable it otherwise I get following error.
XMLHttpRequest cannot load http://127.197.200.100:8000/ManagementAPI/createuser. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.197.200.100:8000' is therefore not allowed access.
This is how I am sending request
CreateUser: function(adata) {
var config = {
headers :{
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
var promise = $http.post(213.187.243.177:8283/ManagementAPI/createuser,adata,config).then(function (response) {
return [response.status,response.data];
},function (response) {
console.log("Error Returned" + response.status);
return [response.status,response.data];
});
return promise;
},
I have tried ThisLink for solution but did not work. Need a solution for accessing it without CORS.
Set headers in back end for avoiding CORS issues .
Sample code in php is shown in below
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Angularjs: Why does adding an authorization header cause a -1 status response?

I have a pre-existing angular code that gets data from an API. I'm trying to add an authentication token to the request.
To begin with I tried a simple example
.factory('getDep', [
'$resource', function($resource) {
return $resource('/ContactsDatabaseAPI/deps/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: false,
headers: {
'Authorization': 'Bearer ' + token
}
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
remove: {
method: 'DELETE'
}
});
}
When the GET call is fired, and F12-ing in Chrome, I get an error message of:
angular.js:11821 OPTIONS http://localhost:56057/ContactsDatabaseAPI/deps net::ERR_CONNECTION_RESET
The return status of -1 and no sign of the call making it to the server side.
Without the headers line, it works fine.
If I try the GET call in Postman with the same Authorization value in the header, this also works fine.
I've also tried to add the header in the httpInterceptor and get the same result:
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + authData.token;
Other things I've tried:
A random header name causes the same issue.
I've added 'Content-Type' = 'text/plain; charset=utf-8' as a header. This has no change to the result
I'm using angular 1.5.6
try this (in the controller) :
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
I've solved my issue and thanks to #Mourad-Idrissi for pointing me in the right direction.
The reason it worked before is that there was no Pre-Flight checks before the API was run. When I added the header, this changed the way the client communicated to the API. Now there was a OPTIONS call to the API which was causing the error. As the domain was different, this introduced me to the world of CORS.
By adding the following to my Application_BeginRequest() method in my backend Web API, Pre-flight now passes and my application continues.
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}

Ionic http post to external url

Im trying to send a post to a url with Ionic using angular, but i have the response:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.
I know that the external service is working, because i tested it by ajax and everything works perfectly...
Below the code used in AngularJS (Ionic) and Ajax:
Ionic:
var loginServiceUrl = 'http://url.com.br'; //It is not the real one
var loginServiceData = {
email: email#email.com.br
senha: 1234
};
$http.post(loginServiceUrl, loginServiceData).
then(function (res){
console.log(res);
});
Ajax:
$.ajax({
type: "POST",
url : 'http://url.com.br', //It is not the real one
data : {email: 'email#email.com.br', senha: '1234'},
success: function(result) {
$('html').text(JSON.stringify(result));
}
});
Does anyone know why I get the post via ajax on my localhost and not with the ionic, also localhost?
Check this out. It is well explained how to handle issues like yours --> http://blog.ionic.io/handling-cors-issues-in-ionic/
Try to add headers in your POST request.
//example of DataToSend
var DataToSend = {
userID: deviceID,
coordLat : pos.coords.latitude,
coordLon: pos.coords.longitude
};
$http({
method: 'POST',
url: 'http://url.com.br',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: DataToSend
})
CORS has nothing to do with your frontend.
Before sending the POST request, browser send a OPTIONS request to the server to check if call from your domain is allowed or not.
Since, you are getting Status 404, that means your server is not handling the OPTIONS request
1. Allow the OPTIONS request (same as POST)
Now come to second part i.e " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' "
After allowing the OPTIONS request, now set the response header of OPTIONS request (Browser will check the response of OPTIONS request and then process the POST request only if there is 'Access-Control-Allow-Origin' present in the OPTIONS response.
2. Set the response headers of OPTIONS request
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
Example..
(In Java)
Router:
OPTIONS /*all
controllers.Application.preflight(all)
Controller Function:
public static Result preflight(String all) {
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Auth-Token");
return ok();
}
Hope this will solve your problem.
Cheers

AngularJs http request header is not changing

I'm getting a problem when I try to call my WebApi, I need to send in a request header the authorization credentials, but, I'm not getting it up.
My resquest header need to be like this image of the request header generated by my REST tester
Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=
But, when I try to set it on Angular using this code block
$http.defaults.headers.Authorization = 'Basic ' + credentials;
return $http.post('http://localhost:2703/api/Authenticate');
Or this
return $http.post('http://localhost:2703/api/Authenticate', {
headers: { 'Authorization': 'Basic ' + credentials }
});
My request header became like this one
Access-Control-Request-Headers: accept, authorization
Can someone tell me what am I doing wrong? Any help will be appreciated. :)
You can do something like this:
var header = {headers: {'Authorization': 'Basic ' + credentials}}
$http.post(url, payload, header)
.success(function (data) {
//stuff
}
I couldn't resolve my problem using a cross domain request, so, I've configure my Web Api and Web App in the same domain. Doing this, I can change the headers normally and send a post request as I need.

Angular JS - $http not sending headers

As the title suggest, I need to pass an authorization token but when I check the network console, I'm getting a 403 because the accept and authorization isn't there. NOTE: I removed my authorization token for this example
$http({
url: 'http://api.stubhub.com/search/catalog/events/v2?title="san"',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": 'application/json',
"Authorization": 'Bearer {token}'
}
}).success(function(response){
$scope.searchResponse = response;
}).error(function(error){
$scope.error = error;
});
This seems like correct syntax? What's wrong here?
EDIT: added the XHR screenshot
EDIT: 2. Here's my network traffic, HAR via paste bin:
http://pastebin.com/fiFngZSy
setting custom headers on XHR requests triggers a preflight request.
I bet you're seeing an OPTIONS request without the Authorization header, and a corresponding response whose Access-Control-Allow-Headers header value is not listing Authorization, or the API doesn't even allow unauthorized OPTIONS requests.
I don't know the stubhub api, but does it return CORS-compliant responses?

Resources