AngularJS get results in error with a 200 response - angularjs

Angular version is 1.3.13
I'm making a url request to a public url to get some data. For one url it functions but for the other it does not. I have no control over the server side.
The URL returns with 200 but AngularJS passes it to the error function. In my browser console the data is there, as JSON, but I do not have access to it in Angular. I was thinking it might the the http.get calling something before passing the data on.
I've tried with plain $http and a custom transformResponse but it still falls to the error of the custom response.
This is the URL:
https://uatmerchant.sixdots.be/oidc/.well-known/openid-configuration
These are the response headers from the URL:
Connection
close
Content-Security-Policy
reflected-xss block
Content-Type
application/json
Date
Mon, 15 Jan 2018 12:33:30 GMT
Set-Cookie
BIGipServer~DMZ~pool_uat_5000=…omain=.uatmerchant.sixdots.be
Strict-Transport-Security
max-age=15552000; includeSubDomains
Transfer-Encoding
chunked
X_CORRELATION_ID
UAT-MER-F5-20180115133330632
X-Content-Security-Policy
reflected-xss block
X-Content-Type-Options
nosniff
X-Frame-Options
SAMEORIGIN
X-Xss-Protection
1; mode=block
This is part of the data that is in the response in the browser console
request_parameter_supported true
claims_parameter_supported false
scopes_supported […]
0 openid
1 profile
2 email
3 address
4 phone
issuer https://uatmerchant.sixdots.be/oidc
acr_values_supported […]
0 tag:sixdots.be,2016-06:acr_basic
Here is the code making the call with the URL that is detailed at the start of this post above
var oohahhel = $sce.trustAsResourceUrl(urlVar);
$http.get(oohahhel)
.then(
function success(response){
var jsonResponse = angular.fromJson(response);
//process response
}
,function error(reason){
//process error
});

Related

CORS issue with angular $http.post - successful requests result in errors with status 0

I'm using angular to POST to an authentication endpoint; on the server side, I can see the request succeed, and proper CORS headers are set. Angular's origin is http://localhost:9000
On the server side, preflight OPTIONS requests always get a 200 back, so that seems OK.
On the client side, the $http.post always fails with an error code of 0, which from other research suggests something is still wrong with CORS. I've read the spec and tried a number of other answers, yet something is still missing.
Angular POSTs like this:
$http({
method: 'POST',
url: 'http://localhost:3000/auth/login',
data: {
username: $scope.username,
password: $scope.password
}
})
.then(function (response) {
/* etc. etc. */
}, function (response) {
/* This always triggers, with response.status = 0 */
console.log("ERROR: " + response.data);
console.log("Status: " + response.status);
console.log("Status text: " + response.statusText);
console.log("Headers: " + response.headers);
$scope.error = 'Something went wrong...';
});
Using curl to debug what the server is sending back, this is it:
< HTTP/1.1 302 Found
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
< Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, Content-Length, X-Requested-With
< Access-Control-Allow-Credentials: true
< Set-Cookie: ua_session_token=(blahblah); Path=/
< Location: /
< Vary: Accept
< Content-Type: text/plain; charset=utf-8
< Content-Length: 23
< Date: Mon, 28 Dec 2015 15:08:17 GMT
< Connection: keep-alive
This is why I'm at a loss, as per the specification, the server seems to be doing the right thing?
Here's what the server gets from the client in terms of request headers:
HEADER host localhost:3000
HEADER content-type application/json;charset=UTF-8
HEADER origin http://localhost:9000
HEADER content-length 38
HEADER connection keep-alive
HEADER accept application/json, text/plain, */*
HEADER user-agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9
HEADER referer http://localhost:9000/
HEADER accept-language en-us
HEADER accept-encoding gzip, deflate
UPDATE tried something else with no luck, based on this post. It would seem Access-Control-Allow-Headers is case-sensitive, and angular is sending on the request accept, origin, content-type. I tweaked the server to parrot back the same, with no luck.
Alright, after applying my head to my keyboard for several hours, I've fixed it.
The answer seems to be that angular really doesn't like getting redirects in response to POST. When I changed the server endpoint to return just a plain auth token as text (the same token it was setting as a cookie anyway) rather than returning a redirect, the angular POST started working like a charm and falling through to the success handler.
Not sure I got deep enough into this to know why angular was behaving in that way; by playing around with it I found that if the redirect the server sent was to a nonexistent (404) URL that this could be replicated, EVEN IF the original POST returned that valid redirect.

AngularJS webapp: how to retrieve a json with the bytes of an image via an http post request

From an AngularJS webapp I do an http post request like this:
Response Headers:
Content-Type is application/json
Request Headers:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form data is:
json:{"id":100,"value":"https://myweb/go/1.0-1/Photo/Spa_03.jpg"}
Response is like:
{"id": 100, "imageBytes": "IMAGE BYTES"} where IMAGE BYTES are the bytes of the image whose URL is supplied in the request.
I get an HTTP success (200) but an error in the angular code (in fromJson / defaultHttpResponseTransform). Error is SyntaxError: Unexpected token.
I suppose that the response content-type is incorrect.
But could someone tell me what I must set ? And how ?
Regards.

Angularjs $http.post() is sending an OPTIONS request only

I've got some Angular code where I am attempting to send a POST to a dev server.
var url = 'http://someDevUrl.com',
data = { 'someKey': 'some value' };
$http.post(url, data);
It sends the OPTIONS preflight request. I can see it hit the server, and the server gives it a happy response.
OPTIONS Response Headers:
HTTP/1.1 200 OK
Server: Cowboy
Date: Mon, 08 Dec 2014 18:20:44 GMT
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 30
Access-Control-Allow-Headers: x-requested-with, content-type, accept, origin, authorization, x-csrftoken
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Via: 1.1 vegur
but then Angular never sends the POST after that...
Typically when $http.post() only sends an OPTIONS request, that means the OPTIONS request returned an error (usually a CORS issue). But in this case, all is fine with the OPTIONS request & response, but it still won't send the POST.
Has anyone seen this before or have an idea of what might be preventing it from sending the POST?
EDIT:
I've got around the issue by adding a Content-Type: text/plain header to the request:
var url = 'http://someDevUrl.com',
data = { 'someKey': 'some value' },
config = {
headers: {
'Content-Type': 'text/plain'
}
}
};
$http.post(url, data, config);
which causes it to skip the OPTIONS preflight, thus avoiding the issue. I'm still curious to know why it was not working in the first place, since there was/is no CORS issue and the OPTIONS request was not sending back an error response.

setting HTTP Header for angularjs REST calls

I'm trying to set a HTTP Header for all my REST calls with following code:
app.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers.Authorization = '12345678';
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
}
return response || $q.when(response);
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
I currently don't have any authorization enabled on the server.
when I leave out the line "config.headers.Authorization = '12345678';" , then the REST call works well and I get my results. In the JS console I see
GET http://localhost:8080/rest/club/1 [HTTP/1.1 200 OK 7ms]
But when I put this line in to set the Header field, then I see following request in the javascript console
OPTIONS http://localhost:8080/rest/club/1 [HTTP/1.1 200 OK 2ms]
Why does setting Authorization Header change my method from "GET" to "OPTIONS"? And how can I set a custom Header and my request still work?
changing it to
config.headers["X-Testing"] = '12345678';
had the same result.
EDIT:
I tried the answer, I'm setting following HTTP Headers in the server:
response.getHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost");
response.getHeaders().putSingle("Access-Control-Allow-Header", "X-Testing");
response.getHeaders().putSingle("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.getHeaders().putSingle("Access-Control-Max-Age", 1728000);
my REST server is running on port 8080, the webserver for the html/JS on port 8000 (initially worked with file://... but moved to a separate webserver because Origin was null)
response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
or
response.getHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
didn't work either.
Must I return any content in the OPTIONS response? I tried 200 OK with the same content as the GET, but I also tried 204 No Content.
2nd EDIT:
here is what firefox sends and receives for the OPTIONS method:
You need to enable CORS in your REST service. As explained in MDN, once you add a custom header, the http protocol specifies performing a preflight,
Preflighted requests
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used
to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted. It sets
custom headers in the request (e.g. the request uses a header such as
X-PINGOTHER)
Addition to enabling CORS you also need to add a Access-Control-Allow-Headers header tag to accept your custom header (for the OPTIONS response). This is visible in the MDN Example,
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain
UPDATE
As mentioned in the comments, the OPTION response's Access-Control-Allow-Headers is missing the last "s".

How to define received datatype, in backbone.js fetch()?

fetch data from server returns me json data as a string datatype rather than as application/json datatype, as a result the collection does not get refreshed.
I have tried giving the jquery.ajax option contentType:"application/json" to the fetch options, but still does not work.
how can i make it work? do i send a mimetype from the server? if so, how?
i am using json_encode on the data sent.
preloader.fetch({
contentType:'application/json'
});
preloader is an instance of my collection.
edit:
my template for a subview was not getting detected as i had kept it out of the masterview's $el element, corrected it, and now i am getting underscore.js error, that
str is null in
str.replace(/\\/g, '\\\\') //at line 913
is this because the backbone app is not taking it as a json object?
Request headers
Connection close
Content-Type text/html
Date Thu, 12 Apr 2012 13:00:58 GMT
Server Apache
Transfer-Encoding chunked
Vary Accept-Encoding
Response headers
has the line
Accept application/json, text/javascript, */*; q=0.01
means it is a json, then what is the problem?
I think the contentType option is for the request (your request).
Try dataType:"json".

Resources