Not able to POST data to RESTFul service from AngularJS - angularjs

Hope some one can help me here.
I am trying to POST a JOSN data to restful service. But am getting below error.
Error:
XMLHttpRequest cannot load http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
This is how i am invoking the service
$http.post('http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam', $scope.strLogiTeam
).success(function(data, status, headers, config) {
console.log("success");
}).error(function(data, status, headers, config) {
// Handle error
console.log(status);
});
My service.
I am not even trying to pull the data. I am just trying to check whether my service is getting invoked or not.
#POST
#Consumes("application/json")
#Path("/PutLogicalTeam")
public void putNewLogicalTeam(LogicalTeam newLogicalTeam)
{
System.out.println("Invoked");
}
I also tried like below
$http({
method: 'POST',
dataType: 'jsonp',
data: $scope.strLogiTeam,
url:'http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam',
headers: {'Content-Type':'application/json'}
});
Can some one review and help. Also suggest the better way to use the web service

Related

AngularJS - Cannot read response headers from $http

My http response contains the headers Authentication (as mentioned here: Authentication:76efbc0946773b62c93e952b502a47acd898200f6f80dc46ac87ffc501c00780) when I inspect the request with the inspector, but a call to headers("Authentication") returns null
return $http({
method: "GET",
url: url,
headers: {
'Content-Type': "application/json"
}
}).success(function (data, status, headers, config) {
console.log(headers("Authentication"));
})
Do you have any idea about what I could be doing the wrong way ?
FYI, i've tried to switch it back to a "promise" way, with .then, and the issue is still the same.
Your code looks good but if it's a CORS request the server needs to include Access-Control-Expose-Headers: {any custom headers} in the response.
There's a previous question/answer with more details: Reading response headers when using $http of Angularjs
In success callback put :
console.log(headers('content-type'));
console.log(headers()); // All headers
I think the first line return a result in your cas.
In the seconde, have you got the 'Authentication' ?
The custom headers will be visible in same domain. In crossdomain case, you need to send Access-Control-Expose-Headers: Authentication, ... header from server.

angularjs basic authentication headers

I'm trying to connect to API and send authentication headers.
I'm using Base64 as described here How do I get basic auth working in angularjs?
function Cntrl($scope, $http, Base64) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('----myusername----' + ':' + '----mypass---');
$http({method: 'GET', url: 'https://.../Category.json'}).
success(function(data, status, headers, config) {
console.log('success');
}).
error(function(data, status, headers, config) {
alert(data);
});
}
but i'm getting this error
XMLHttpRequest cannot load https://.../Category.json?callback=?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://....com' is therefore not allowed access. The response had HTTP status code 400.
Looks like you are running into issues with Cross-Origin Resource Sharing (CORS). Have a read of:
How does Access-Control-Allow-Origin header work?
If you control the server then you can have it send back an appropriate Access-Control-Allow-Origin header as per what the server code in the question you referenced (How do I get basic auth working in angularjs?)

AngularJS POST fails with No 'Access-Control-Allow-Origin' when using data payload object but works using query params like payload

I am facing a weird issue. I am running my angularjs app in nodejs server locally which calls a POST API from my app located on Google App Engine. The API is configured with all CORS headers required as follows:
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers.add_header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With, content-type, accept, myapp-domain")
self.response.headers["Content-Type"] = “application/json; charset=utf-8”
GET requests to the API work without issues.
POST requests to the API work but ONLY when I send the post data as a 'string of params' and NOT when post data is sent as an object which is the right way to do. Eventually I need to be able to upload pictures using this API so the first solution below might not work for me. Please help!
METHOD 1: This works:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = "conversationid=1c34b4f2&userid=67e80bf6&content='Hello champs! - Web App'";
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz",
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
METHOD 2: This fails:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = ({
'conversationid' : '1c34b4f2',
'userid' : '67e80bf6',
'content' : 'Hello champs! - Web App'
});
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz"
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
When I use METHOD 2 it fails with the following error in the console:
XMLHttpRequest cannot load https://myapp-qa.appspot.com/message.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://0.0.0.0:8000' is therefore not allowed access.
Please let me know if you have any solution. Thanks in advance.
The issue is most likely with Angular sending a pre-flight OPTIONS request to check the access headers from the server. I am not sure how OPTIONS requests are handled in your API, but I am betting these headers are not being added. I suggest installing Fiddler to monitor the actual requests to see what is going on with the headers. You may only be adding them to your POST responses.
See this answer for details on why METHOD 1 may work in this scenario, while METHOD 2 does not.
Here are some more details about pre-flight requests.

Getting JSON data using Angular JS's $http service

I need to get JSON data from a server with URL :
http://xxxx.xxxx.xxxx.xxxx:8084/inpulse/api/user/listall
Here's my angular code:
var app = angular.module('app',[]);
app.controller('Controller', function ($scope,$http) {
$scope.email="";
$scope.password="";
$scope.sample="";
$http({
method: 'GET',
url: 'http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall',
})
.success(function (data, status, headers, config) {
var ret = data;
$scope.sample = JSON.stringify(ret);
})
.error(function (data, status, headers, config) {
alert(status);
// something went wrong :(
});
});
Now the same code worked when i used a JSON test URL like http://ip.jsontest.com/.
Its Definitely not a problem with the server because I tested it with a REST client and got a response. I can't figure out what I'm doing wrong.
It might be a CORS configuration issue.
If you are trying to access the server from a page that is not in the same domain/origin, you'll get an error because the server is not configured to allow CORS.
The error reported by Chrome looks like this:
XMLHttpRequest cannot load http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Other than that the code seems to work just as expected.

What is the correct architectural pattern for cross domain REST call in AngularJS?

I've created an AngularJS service that is hitting the Salesforce REST API directly from the client. However, I haven't been able to get it working due to same origin restrictions. Even when accessing non authenticated REST services and trying both $http, $http.json and Ajax. I've also tried lots of combinations of Json, Jsonp etc.
Given that I've had so many issues I'm thinking that my general approach is incorrect. Perhaps I need to setup a proxy server for this? My backend is Firebase so I don't currently have my own server.
I don't believe that the Salesforce API supports CORs and I cannot change that.
Here is an example of what I tried using $http and Ajax.
return $http.jsonp('https://na1.salesforce.com/services/data/',{
headers: {
'Content-type': 'application/json', 'Accept': 'application/json'
}}).
success(function (data, status, headers, config) {
callback(data);
console.debug(data.json);
}).
error(function (data, status, headers, config) {
console.debug("getVersions: failed to retrieve data: "+eval(data));
});
$.ajax({
url: 'https://na15.salesforce.com/services/data',
type: "GET",
dataType: "jsonp",
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
xhrObj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
},
success: function (data) {
console.debug(data);
callback(data);
},
error: function(data) {
}
});
You need to go into Remote Settings within SalesForce then CORS and whitelist the domain name...
I had the same issue and it seemed to have resolved the issue.
See if this helps here

Resources