First of all, I have whitelisted my localhost port 3000 for Cross-Origin requests. I am building a MEAN stack application. And I am trying to consume an API using $http service.
myApp.controller('minuteController', function($scope,$http) {
$scope.submitButton = function() {
$http({
method: 'POST',
url: 'https://url.example.com/server/oauth/token?grant_type=password&username=username&password=pass1234&origin=local',
headers: {'Authorization':'Basic asdsadsads=','Content-Type': 'application/json; charset=UTF-8','Accept':'application/json, text/plain,*/*'}
})
.then(function successCallback(response) {
$scope.dataDisplay = response.data;
console.log(dataDisplay);
});
}
});
If I use the same details to make an XMLHttpRequest it works fine. Below is the code that works.
var xmlhttp = new XMLHttpRequest();
var url = "https://url.example.com/server/oauth/token?grant_type=password&username=username&password=pass1234&origin=local";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myObject = JSON.parse(xmlhttp.responseText);
alert(myObject);
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type","application/json;charset=UTF-8");
xmlhttp.setRequestHeader( "Accept","application/json, text/plain, */*");
xmlhttp.setRequestHeader( "Authorization","Basic asdsadsads=");
xmlhttp.send();
Finally found the problem. It's solved my problem by adding data: ''
in the argument to $http.