AngularJS $http date header - angularjs

I'm trying to retrieve the $http date header from an AngularJS $http.get request so I can get the server time.
app.controller('MainCtrl', function($http,$scope) {
$scope.name = 'World';
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
console.log(response);
})
});
I can't seem to retrieve the Date header although when I inspected on chrome tools the date header was there.

try this:
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
var data = response.data,
status = response.status,
headers = response.headers(),
config = response.config;
})
headers will contain:
headers: {
"date": "Mon, 02 Mar 2015 23:02:51 GMT",
"content-encoding": "gzip",
"server": "Apache",
"vary": "Accept-Encoding",
"content-type": "text/html",
"connection": "Keep-Alive",
"keep-alive": "timeout=10, max=500",
"content-length": "39"
}
to access date:
headers.date
Since it's a CORS request to facebook api: The response header will contain only
Content-Type
Last-modified
Content-Language
Cache-Control
Expires
Pragma
The issue is because of missing Access-Control-Allow-Headers from request Header. To fix this we need to add Access-Control-Allow-Headers: * to request header in your run method

Related

I am trying to upload a file to Django server using angularjs 1.6.5. I am not able to upload file using $http.patch method

Using Angularjs 1.6.5 I am trying to upload a file to the Django server. When I try to upload the file I am not sure what type of 'Content-Type' header should be passed with the $http.patch method. Here is the following my Angular apps config:-
var app = angular.module("edit_modules", []);
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
});
And this is my patch method:-
$http.patch(url, data, {
headers: {'Content-Type': 'application/json; charset=utf-8' }
}).then(successCallback, errorCallback);
function successCallback(response){
console.log("Success");
console.log(response);
};
function errorCallback(error){
alert("Error Uploading!");
console.log(error);
};
When I pass {'Content-Type': 'application/json; charset=utf-8' } through the Header I get the following error:-
"The submitted data was not a file. Check the encoding type on the form."
Status :- 400
Since its content-type is file I used the following header {'Content-Type': 'multipart/form-data; charset=utf-8'} . But then I got this error:-
Multipart form parse error - Invalid boundary in multipart: None
Status :- 400
As suggested in the link here I tried the following header as well {'Content-Type': undefined} But this as well did not resolve my problem and I got the following error:-
Unsupported media type "text/plain;charset=UTF-8" in request.
Status :- 415
However when I tried with simple text fields the PATCH method worked with the header supplied being {'Content-Type': 'application/json; charset=utf-8' }. I am not sure where the problem is. I even tried to see the console for what data was being set to be patched
data = {
"video": element.files[0]
};
console.log(data);
THIS is what i got on console:-
{video: File(99861)}video: File(99861) {name: "Capture2.PNG", lastModified: 1517491665223, lastModifiedDate: Thu Feb 01 2018 18:57:45 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 99861, …}
any help is much appreciated.
Referring to the answer here I found that you need to attach the File Object to be sent using FormData. Also you need an additional header in config transformRequest: angular.identity,. Here is the successful PATCH method that worked for me.
var fd = new FormData();
fd.append('video', element.files[0]);
$http.patch(url, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(successCallback, errorCallback);
function successCallback(response){
console.log("Success");
console.log(response);
};
function errorCallback(error){
alert("Error Uploading!");
console.log(error);
};
In the second line 'video' is the REST API Endpoint's variable where my file will be stored. In order to avoid the error
Multipart form parse error - Invalid boundary in multipart: None
I have left the headers: {'Content-Type': undefined}.

Fetch Angular $http response header param

I am working on an Progressive Web app module with AngularJS.
I have made a network call with POST request using '$http', I am able to get a response of it but am not getting 'Response Header' params.
Here is my Response header:
Connection:keep-alive
Content-Type:application/json
Date:Fri, 19 May 2017 10:41:49 GMT
Server:JBoss-EAP/7
Session-ID:XXXXX-YYYY-ZZZ
Transfer-Encoding:chunked
X-Powered-By:Undertow/1
And below is a request and API call.
$scope.data = {userid: $scope.username,
os: 'android',
device_id: 'b0316b93ae786ec0',
source: 'iv2',
password: $scope.password,
build_version_code: '2.3',
version: '5.1.1'};
$http({
method : "POST",
url: 'https://domain.name/v1/users/login',
data : $scope.data,
headers: {
'content-type': "application/json",
'sessionID': ''
}
})
.then(function successcallback(response){
console.log("Session-ID" , response.headers());
console.log("response" , response);
}, function errorcallback(response){
console.log('error' , response);
});
I have tried below possible solution based on response callback method.
function successcallback(response){
response.header('Session-ID');
}
and
success(function(response , status , headers , config){
console.log("response" ," headers - " + headers('Session-ID'));
}
The both approaches returns a null value instead of expected value.
Please let me know if I am missing something. I am happy to get all possible help.

How to setup e2e protractor backend request mocking/stubbing

I try to setup my independent protractor project to mock some of my backend requests. Therefore, I included angular-mocks.js and attached another module within the onPrepare() function of my protractor.conf.js:
browser.addMockModule('httpBackend', function() {
angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
$httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
var obj = {"msg": "Response!"};
return [200, JSON.stringify(obj), {}];
});
})
})
This lets me intercept any request but I am not getting what I want to return in respond(). It seems I am just getting a 200 OK.
What am I doing wrong?
Just to let you know how I solved it:
The docs say the following:
The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).
In my case, the headers Object somehow does not seem to be optional and I ended with setting it on my own before returning the array:
browser.addMockModule('httpBackend', function() {
angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
$httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
var obj = {"msg": "Response!"},
resHeader = {
"Cache-Control": "no-cache, no-store, max-age=0",
"Date": "Tue, 24 Nov 2015 17:08:57 GMT",
"Pragma": "no-cache",
"Transfer-Encoding": "chunked",
"Content-Type": "application/json; charset=UTF-8",
"Expires": "Thu, 01 Jan 1970 00:00:00 GMT",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "origin,x-requested-with,access-control-request-headers,content-type,access-control-request-method,accept",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, DELETE",
"Access-Control-Credentials": "true",
"Content-Language": "de-DE",
"Access-Control-Max-Age": "3600"
};
return [200, JSON.stringify(obj), resHeader];
});
})
})
Anybody has a clue why this is necessary or which of its attributes is obsolete?

angularjs how to post key/values not json object

I hava a json object in my ctl:
$scope.disease
and anyone can edit it's properties and then post to server.
when save it,
$scope.save = function(){
$http.post('/***', $scope.disease)
}
however, the request body is as a json string.
while I want it to be as form data:
key1: value1
key2: value2
key3: value3
how can I do?
thanks a lot
after I set the Content-Type like this:
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}])
the request header:
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/x-www-form-urlencoded; charset=UTF-8
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
however the post parameter like this:
{"age":56,"birthday":"1958-07-14","familyHistory":"********************","id":1,"illness":"*********************","illnessHistory":"***************************","number":"21","selfDescription":"***********************"}
Because the $scope.disease is:
{
"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"
}
while the post parameter should like this:
"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"
Do you understand me?
Finally I add a transformRequest method to post-request:
$httpProvider.defaults.transformRequest=function(obj){
var str =[];
for(var p in obj){
str.push(encodeURICompent(p)+'='+encodeURICompent(obj[p]));
}
return str.join('&');
}
Then the problem solved!
In the $http.post call, add a correct Content-Type header to the config object (third parameter). If left empty, Angular defaults to a JSON payload.
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
Set the Content-Type attribute of the header to application/x-www-form-urlencoded using the $httpProvider on your config or do it for each request on the $http service.
You can do it in below mentioned ways
this.createOrder = function(userId,accountId,deliveryDate,cutOffDateTime,customerRef){
var orderCreateURL = contextProp.baseURL + '/users/'+userId+'/account/orders';
return $http({
method: 'POST',
url: orderCreateURL,
data:{
'accountId': accountId,
'deliveryDate':deliveryDate,
'cutOffDateTime':cutOffDateTime,
'customerRef':customerRef
}
});
};
It will post your data in key,value pairs. You can also specify the headers i.e. headers: {'Content-Type': undefined } and transformRequest: angular.identity etc.. in parameters same as any other HTTP requests. Thanks.

How to read response headers with $resource?

I'm using $resource to get data from my RESTful service and I need to read response headers to get 'X-Page' and 'X-Total-Pages' value for pagination.
Example:
Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:2637
Content-Type:application/json
Date:Thu, 10 Apr 2014 16:53:01 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
Vary:Origin
X-Page:1
X-Per-Page:10
X-Total:17
X-Total-Pages:2
But I couldn't get full headers from server.
This is returned headers:
This is the headers from server:
This is my code:
.factory('TestAPI', ['$resource',
function ($resource) {
return $resource("http://ip.jsontest.com/?callback=showIP", {}, {
query: {
method: 'GET'
}
});
}])
TestAPI.query({}, function (value, responseHeaders) {
console.log(responseHeaders());
}, function (response) {
console.log(response);
});
In your response headers you have to add the following header:
Access-Control-Expose-Headers: X-Total-Pages, X-Page
With this, the browser is capable to expose your customs headers an read it angular.

Resources