Handling REST errors in AngularJS - angularjs

I have written a REST service that deals with errors like this:
return Response.status(vr.responseStatus).entity("Oh No")
.type(MediaType.APPLICATION_JSON).build();
On the client side, I have called this:
var request = $http({
method: "put",
url: serviceProvidersURL,
params: {
//action: "add"
},
data: item
});
return( request
.then( handleSuccess,
function(response){
alert("Here1: " + response);
alert("Here2") + JSON.stringify(response);
})
);
Both the alerts are failing to deal with the response. In the first alert, I get "Here1: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" and the second alert, I just get "Here2"
If I look at the response in firebug, the "Oh No!" is in the response section and these are the headers:
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 08 Jun 2016 06:49:57 GMT
Connection: close
The Oh No! is definitely in the response body - I have no idea how to get to it through the client side.
Thanks

Related

API Gateway - 200 response from Postman, 500 from app

I have an API on AWS API Gateway that takes a POST request and forwards headers and body to a third party API and returns the result. This process works fine when I send the request from Postman, but doesn't work either via cURL or JavaScript.
NB - all URIs, auth tokens etc below are modified so may be inconsistent between screengrabs.
The request in Postman is below
Postman console for this looks like
POST https://dsvdvsdvsdrc.execute-api.eu-west-1.amazonaws.com/Prod/
200
957 ms
Network
Request Headers
Authorization: Basic <myauthtoken>NTAwYTQxNDdmYzcyLWFkZDgtNDZmMy05ZWU0LWQzYWM=
Content-Type: application/x-www-form-urlencoded
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Cache-Control: no-cache
Postman-Token: 9dab6f01-67bf-4611-8d8e-c3d5fe725067
Host: tsfsfsdrc.execute-api.eu-west-1.amazonaws.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 82
Request Body
grant_type: "client_credentials"
scope: "https://api.ebay.com/oauth/api_scope"
In my JavaScript app I have the following code:
var data = qs.stringify({
'grant_type': 'client_credentials',
'scope': 'https://api.ebay.com/oauth/api_scope'
});
var config = {
method: 'post',
url: 'https://fddgdgddrc.execute-api.eu-west-1.amazonaws.com/Prod/',
headers: {
'Authorization': 'Basic sssscyLWFkZDgtNDZmMy05ZWU0LWQzYWM=',
'Content-Type': 'application/x-www-form-urlencoded'
},
data : data
};
console.log("******Here is ebayData REQUEST***** "+ JSON.stringify(config));
axios(config)
.then(function (response) {
console.log("******Here is ebayData***** "+ JSON.stringify(response.data));
})
.catch(function (error) {
console.log( "******Here is ebay Error***** "+ error);
});
However when the application runs I get a 500 response. Below are the request headers and body that is being sent in the request
I've enabled cloudwatch logs on the API and below is an example of a successful request via Postman
and here is an example of an unsuccessful request from the browser
Looking further into the response headers for a failed and a successful response I see the headers with comments against them are different
Failed request
(d360923b-eff2-433f-8f76-a9038547dcdf) Endpoint response headers: {rlogid=t6ldssk67%3D9whhldssk67*qc1qr%28rbpv6710-17dd35648ce-0x129,
x-ebay-c-version=1.0.0,
x-frame-options=SAMEORIGIN,
x-content-type-options=nosniff,
x-xss-protection=1; mode=block,
set-cookie=ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/; Secure,dp1=bu1p/QEBfX0BAX19AQA**6581b87b^;Domain=.ebay.com;Expires=Tue, 19-Dec-2023 15:36:27 GMT;Path=/; Secure,
content-encoding=gzip,
cache-control=private, <--- doesn't appear in successful response
pragma=no-cache, <--- doesn't appear in successful response
date=Sun, 19 Dec 2021 15:36:26 GMT,
server=ebay-proxy-server,
x-envoy-upstream-service-time=19,
x-ebay-pop-id=UFES2-RNOAZ03-api,
transfer-encoding=chunked}
Successful request
(fe565553-3283-4593-8b07-b4e2d58dd2a6) Endpoint response headers: {rlogid=t6ldssk67%3D9vjdldssk67*5cddm%28rbpv6775-17dd23fa53c-0x124,
x-ebay-c-version=1.0.0,
x-ebay-client-tls-version=TLSv1.2,<--- doesn't appear in failed response
x-frame-options=SAMEORIGIN,
x-content-type-options=nosniff,
x-xss-protection=1; mode=block,
set-cookie=ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/; Secure,dp1=bu1p/QEBfX0BAX19AQA**65817126^;Domain=.ebay.com;Expires=Tue, 19-Dec-2023 10:32:06 GMT;Path=/; Secure,
content-encoding=gzip,
content-type=application/json,<--- doesn't appear in failed response
date=Sun, 19 Dec 2021 10:32:06 GMT,
server=ebay-proxy-server,
x-envoy-upstream-service-time=96,
x-ebay-pop-id=UFES2-SLCAZ01-api,
transfer-encoding=chunked}
I think I've been looking at this for too long and am probably missing something obvious, but headers and body etc all seem to be consistent across the app and Postman, so I'm confused why the request from one is successful and the other is failing. Any advice much appreciated.
Add all other headers as in Postman , some application rejects requests without proper user-agent header or some other required headers.

$http content-type: application/json throws 500 internal server error

I am making a post call like below with default content-type: application/json
But it throws
500 internal server error.
Should I change the content-type or encode the request data I send.
I tried using Content-Type:
application/x-www-form-urlencoded; charset=UTF-8.
which didn't turn out well
$http(
{
url: '/api/sitecore/Appointment/AppointmentConfirmation',
method: 'POST',
data: "__RequestVerificationToken":"7zK0TTYLMpMtsKl11vVKI-vTK5-Mz-ViAqNKqL-aSLv3SKLCu807C10e9z8FkSFF0Av2NWeaI8R47CuBtNND6cA1"
}
)

how can i use angularjs to request for a RESTful token

I would like to do a token request from angular like below:
http --auth <email>:<password> --json GET http://127.0.0.1:5000/api/v1.0/token
the above is httpie, description below:
--auth, -a Pass a username:password pair as the argument. Or, if you only specify a username (-a username), you’ll be prompted for the password before the request is sent. To send a an empty password, pass username:. The username:password#hostname URL syntax is supported as well (but credentials passed via -a have higher priority).
--auth-type Specify the auth mechanism. Possible values are basic and digest. The default value is basic so it can often be omitted.
here is the output of the above command:
root#localhost:/var/www/myapp# http --auth myname#email.com:thepassword --json GET http://127.0.0.1:5000/api/v1.0/token
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 159
Content-Type: application/json
Date: Wed, 25 Nov 2015 03:13:16 GMT
Server: nginx/1.4.6 (Ubuntu)
Set-Cookie:session=eyJfaWQiOnsiIGIiOiJOR000TkdGak1UQTFabUppTldNeE1HVTBZemt3TjJWaU1EVmpNemN4WkdZPSJ9fQ.CTa4zA.YoXlQf5H68q3lRzuAEmEQ5kRm_I; HttpOnly; Path=/
{
"expiration": 0,
"token": "eyJhbGciOiJIUzI1NiIsImV4cCI6MTQ0ODQyNDc5NiwiaWF0IjoxNDQ4NDIxMTk2fQ.eyJpZCI6MX0.NY5hSBVjeddctBVvlM1cDJw2A9Yv38om5cqyBQUQhgU"
}
below is the code i have on angularjs:
$scope.login = function() {
var config = {
method: 'GET',
url: '/api/v1.0/token',
headers: {'auth':'myname#email.com:thepassword'}
};
$http(config)
.success(function(data, status, headers, config) {
if (data.status) {
//logged in
}
else {
//failed
}
})
.error(function(data, status, headers, config) {
//failed
});
}
i hard-coded with the email and password to the code, so when i click on the button, it should use the email/password to get the token from the server with the correct output like above, but instead, i got this:
Failed to load resource: the server responded with a status of 401 (UNAUTHORIZED)
I don't know what went wrong, please correct me if i missed anything.
Thanks.

Angular JS - Blank Error Response

I am learning Angular JS and am facing an issue with an the HTTP Get Request. Here is my code:
function countryController($scope,$http) {
delete $http.defaults.headers.common['X-Requested-With'];
$http.get("http://localhost:8080/countrybook/api/v1/countrybook")
.success(function(response) {
$scope.countries = response;
})
.error(function(response){
alert(response);
});
}
I get a blank error response (alert with nothing in it. when i debug in firebug i see that response is "") for some reason.
My headers look like this:
Response Headers:
Cache-Control private, must-revalidate
Content-Length 355
Content-Type application/javascript
Date Sat, 15 Nov 2014 16:53:52 GMT
Last-Modified Sat, 15 Nov 2014 16:52:06 GMT
Server WebStorm 9.0.1
Request Headers:
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Host localhost:63342
If-Modified-Since Sat, 15 Nov 2014 16:52:06 GMT
Referer http://localhost:63342/CountryBook/index.html
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
and the Response that I see in Firebug is this:
function countryController($scope,$http) {
delete $http.defaults.headers.common['X-Requested-With'];
$http.get("http://localhost:8080/countrybook/api/v1/countrybook")
.success(function(response) {
$scope.countries = response;
})
.error(function(response){
alert(response);
});
}
Could you please help me figure out whats wrong? When I use the same link mentioned above in the http get request directly from the browser I see the response that I expect. Thanks for your help!
The problem was:
The Same Origin Policy disallows reading the remote resource at localhost:8080/countrybook/api/v1/countrybook. This can be fixed by moving the resource to the same domain or enabling CORS.
Solved it by adding these two headers at the server side response:
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
Smartbart24 - looking at the console logs helped. Thanks for your help!
So without knowing your backend my general $http pattern is:
$http.get(requestEndpointString)
.success(function(data,status,headers,config){
if(status!=200){
/*unexpected response status ...*/
console.log('API error status: '+status);
}else{
/* Success ... */
}
})
.error(function(data, status, headers, config){
/* Handle errors */
});
Maybe it helps you to debug with logging the response status ?
Also try to take out the line:
delete $http.defaults.headers.common['X-Requested-With'];

error fetching backbone model (works in chrome but not in firefox and ie9)

I have one service that returns proper data in chrome but ends in error for firefox and ie9. It looks like the GET returns 200 OK code, but still ends in error callback. I'm fetching data via backbonejs (with jquery.getJson and with ajax I'm getting the same result). The same result I'm getting also if I try to fetch data from remote server or locally.
Chrome: Version 23.0.1271.64 m
FF: 16.0.2
IE9: 9.0.8112.16421
wcf:
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/getData/{name}", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
List<Names> getData(string name);
serviceUrl:
"http://serverABC:4000/myService.svc/getData/test"
fetching from javascript:
via backbone or jqueryGetJson():
$.getJSON("http://serverABC:4000/myService.svc/getData/test", function () {
alert("success");
})
.success(function () { alert("second success"); })
.error(function (result) {
console.log('error:', result);
})
result:
"http://serverABC:4000/myService.svc/getData/test 200 OK 70ms"
headers:
Response Headers
Cache-Control private
Content-Length 6544
Content-Type application/json; charset=utf-8
Date Fri, 16 Nov 2012 14:09:46 GMT
Server Microsoft-IIS/7.5
Set-Cookie ASP.NET_SessionId=s3aguluzip0dw135glbxlwwf; path=/; HttpOnly
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Host svgwbip93:4000
Origin http://localhost:51280
Referer http://localhost:51280/Default.aspx?ReturnUrl=%2f
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0
result from debug:
readyState 0
responseText ""
status 0
**statusText "error"**
abort function()
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function()
overrideMimeType function()
pipe function()
progress function()
promise function()
setRequestHeader function()
state function()
statusCode function()
success function()
then function()
toString function()
Response: - is empty (this is most probably the problem (but as I mentioned in Chrome I'm getting correct json data)
EDIT 1:
I tried to get raw response with fiddler and I'm getting the JSON. The big question is that why callback falls to error.
Here is my raw response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 29
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=kuv3g0r2dgmu5bpaoayj5lic; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 16 Nov 2012 19:32:58 GMT
{"PlatformDrawingsResult":[]}
I verified the json - it seems OK, so what can be the problem....hmm. I forgot to mention that I'm using also requirejs (not sure if that will bring some light,..)
Cheers, Miro
The solution is (thanks to jwkeenan) :
I put this line at the beggining of each method in my web service and
now all browsers work.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
and to get it to work in ie9 I needed to add this to my web app:
$.support.cors = true;

Resources