AngularJS - get headers in response - javascript

I'm doing a $http.get request to a https service which has an XML file and it need the headers('Content-length') to know it size.
This's my code:
$http({
method : "GET",
url : "https://url.com/xml_file.xml"
}).then(
function sCallback(data, status, headers, config, statusText) {
console.log( headers('Content-Length') );
}, function eCallback(data, status, headers, config, statusText) {
$log.warn(data, status, headers, config, statusText);
});
The result of the request is: "headers is not a function".
Is there another way to get it?

console.log( data.headers('Content-Length'));
console.log( data.headers('Content-type'));

Related

Response header is present in browser but not parsed by Angular $http response.headers()

In our Angular app, we need to parse response headers of some $http.
In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35.
Opening the Network tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35 is present.
in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http.
Is there a way to access in $http the 'raw' response and write our custom parser for the header?
$http.({method: 'GET', url: apiUrl,)
.then( function(response){
console.log('headers: ', response.headers());
console.log('results header: ', response.headers('X-Total-Results'));
// ...
})
console output
headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}
results header: null
The reason you can't read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header.
Your server needs to send this header:
Access-Control-Expose-Headers:X-Total-Results
To answer your question in the comments, The Access-Control-Allow-Headers does not allow wildcards according to the W3 Spec
Use $httpProvider.interceptors you can intercept both the request as well as the response
for example
$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
return {
'responseError': function (response) {
console.log(response.config);
},
'response': function (response) {
console.log(response.config);
},
'request': function (response) {
console.log(response.config);
},
};
}]);
Update : You can retrive your headers info in call itself
$http.({method: 'GET', url: apiUrl)
.then( (data, status, headers, config){
console.log('headers: ', config.headers);
console.log('results header: ', config.headers('X-Total-Results'));
// ...
})

How to get request url in an angularjs $http request

I have this request:
$http({
method: 'get',
url: '/api/items/',
params: {a: 1, b: 2, c: 3}
}).success(function (response) {
console.log(response);
}).error(function (err) {
console.log(err);
});
Is there a way, to fetch the url it used to make the request after the request has been made(in the callback or otherwise)?
I would want the output:
http://www.example.org/api/items?a=1&b=2&c=3
Here the same thing is done with jquery.
The success handler gets 4 parameters passed into it:
$http
.get({ url: '/someUrl', params: { q: 3 } })
.success(function(data, status, headers, config) {});
The fourth parameter config has the following properties:
{
method: "GET",
url: {
url: '/someUrl',
params: {
q: 3
}
}
}
You can use window.location.origin to get the base url and build a simple function to concat it all together.
This function should yield the expected response:
var baseUrl = window.location.origin;
var query = [];
Object.keys(config.url.params || {}).forEach(function (key) {
var val = config.url.params[key];
query.push([key, val].join('=')); // maybe url encode
});
var queryStr = query.join('&');
var fullPath = baseUrl + config.url.url + '?' + queryStr;
Unfortunately, this function will only work as long as the parameters are passed in the format described above. If you pass them in a different format, you'll have to modify this function a bit. You can use this as a playground.
Afaik, there is no simpler way. At least a feature request exists.
See the docs of $http for reference
This config parameter of the callback has the url as a property:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
console.log(config.url);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Based on: https://docs.angularjs.org/api/ng/service/$http
You can use http request Interceptor.
Configure the Interceptor in config function using $httpProvider
Whrein for request Interceptor you can able to see the URL and params that you passed with URL prior to making the request
try just looking at the XHR Request urls in your browser dev tools

AngularJS JSONP SyntaxError: Unexpected token :

I am trying to use the WordsAPI and everytime I try to access it using jsnop and Angular I get this error:
The code I am using is the following:
$scope.searchWord = function() {
var url = 'https://www.wordsapi.com/words/'+$scope.word+'/definitions?callback=JSON_CALLBACK&accessToken=ACCESS_TOKEN';
$http.jsonp(url).
success(function(data, status, headers, config) {
$scope.meanings = data;
console.log($scope.meanings)
}).error(function(data, status, headers, config) {
console.log(data);
});
}
So it should be getting something like:
https://www.wordsapi.com/words/word/definitions?callback=JSON_CALLBACK&accessToken=ACCESS_TOKEN
I tested this link on JSON validators and everything is fine with the JSON it gets from the server.
I am using Chrome on a Mac.
Does Anyone have any idea ?

jQuery.ajax to $http

I used this function
jQuery.ajax({
type: 'POST',
url: urlSubmit,
timeout: 5000,
dataType: 'text',
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
"success": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX success :) - statut " + textStatus);
$timeout(successMailZR_alerte, 3000);
},
"error": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX fail :/ - statut " + textStatus);
$timeout(errorMailZR_alerte, 3000);
}
});
Whats the code is doing : code POST to a php script who send an email.
but, since i rewrited my code in a complete angularjs app, i do it like this :
$http({
method: 'POST',
url: urlSubmit,
timeout: 5000,
cache: false,
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'text',
}).
success(function(data, status, headers, config) {
console.log("AJAX success :) - statut " + status);
$timeout(successMailZR_alerte, 3000);
}).
error(function(data, status, headers, config) {
console.log("AJAX fail :/ - statut " + status);
$timeout(errorMailZR_alerte, 3000);
});
Problem is : with $http, i have a success 200 but nothing is posted and i have no return in my email. What's the problem ?
The problem is that jQuery's POST does send your data as form data (e.g. key-value pairs) (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) whereas AngularJS sends your data in the request payload. For a difference between the two see the following SO question: What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
In order to make your angular script works with your server you have to convert your data to a URL encoded string as described here: How can I post data as form data instead of a request payload?. Simply setting headers: {'Content-Type': 'application/x-www-form-urlencoded'} is not enough.
A different approach would be to adapt the back-end of your application to parse the message payload instead of the form data parameters.
To understand this one need to understand the request headers set by angular and jquery, There are differences with the headers like when request is post by jQuery then header might look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John
You can see this in form data in the request made in the browser, if you use chrome then you can see this in chrome inspector at network tab, if you click the request then you can see the form data and content headers set by the jQuery.
On the other side with angular js $http service, when a request is made then you can find these:
POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular
{ "foo" : "bar", "name" : "John" }
The real difference is this you have a request payload not usual form data which is used by jQuery. so you need to do something extra at the server side like below.
Use this:
$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent
This is due to its default headers
Accept: application/json, text/plain, * / *
Content-Type: application/json
and jQuery unlikely have something else:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

AngularJS, POST and GET XMLdata

simple question, how would I write this in javascript/AngularJS.. this pythonscript works:
xml = <data><user>blabla</user> ..... etc
url = 'http://localhost:3080'
response = urllib2.urlopen(url, xml)
print response
Long story:
I'm playing around with an old, legacy XML service and thought it could be fun to get something working with AngularJS. I might confess that I'm not that familiar with either Angular or Javascript, please bear with me.
The XMLservice expects files with data and instructions on what functions to run etc. It will then respond with another xml file with the answer. However, I can't get the simplest function (login) to work at all.
If I try a "GET" and play with params, the service is triggered but logs "invalid" since it's either missing the XML data or the Xmldata is messed up (when added as param)
angular.module('myApp.loginServices', []).
factory('LoginSource', ['$http',function($http){
return {
get: function(url, callback, transform){
$http.get(
url,
{transformResponse:transform}).
success(function(data, status) {
console.log("success!!!!!!" + status+ " data");
callback(data);
}).error(function(data, status) {
console.log("FAILED!!!! " + status);
});
So I try a POST, like this, and this one gives me "status 0" and XmlService logs "501", maybe my xml is messed up or something, but it looks like it's not even reaching the service according to the logs?
factory('LoginSource', ['$http',function($http){
return {
get: function(url, callback, transform, xmlData){
console.log('xmlData: ' +xmlData);
$http({
url: url,
method: "POST",
data: xmlData,
headers: {'Content-Type': 'application/x-www-rform-urlencoded'}
}).success(function (data, status, headers, config) {
callback(data);
}).error(function (data, status, headers, config) {
console.log('status: ' +status);
});
}
};
I guess it's me being too much of a rookie with javascript and angularJs.. any help appreciated

Categories