I am getting below object by rejection.headers() function in responseerror object of interceptor but unable to get particular header value in angularjs code for example x-request-id value have to store in some variable but unable to do that can any one please suggest,
{pragma: "no-cache", date: "Thu, 06 Sep 2018 14:57:56 GMT", x-content-type-options: "nosniff", x-request-id: "VLCRpt3v", x-frame-options: "DENY", …}
cache-control
:
"no-cache, no-store, max-age=0, must-revalidate"
content-type
:
"application/json;charset=UTF-8"
date
:
"Thu, 06 Sep 2018 14:57:56 GMT"
expires
:
"0"
pragma
:
"no-cache"
referrer-policy
:
"same-origin"
transfer-encoding
:
"chunked"
x-content-type-options
:
"nosniff"
x-frame-options
:
"DENY"
x-request-id
:
"VLCRpt3v"
x-xss-protection
:
"1; mode=block"
and trying below code in angularjs code :
var head = rejection.headers();
var requestId = head.x-request-id
You'd better create an Interceptor and push it to to $httpProvider interceptor.
Here is what it should look like:
angular.module('app')
.service('headerRetrieveInterceptor', function ($q) {
var service = this;
service.responseError = function (response) {
// Here Are Your Headers
console.log(response.headers());
return $q.reject(response);
};
}).config(function($httpProvider) {
$httpProvider.interceptors.push('headerRetrieveInterceptor');
})
Related
I'm trying to use the $http service in a angularJS app but I'm getting the below error in my console.
XMLHttpRequest cannot load http://example.com/data.service/getSomething/hghfg7igb757. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://other-example.dev' is therefore not allowed access.
This is my AngularJS Controller:
app.controller('mainController', ['$scope', '$http', function($scope, $http){
var url = 'http://example.com/data.service/getSomething/hghfg7igb757';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).
success(function(status) {
//your code when success
$scope.data = data;
}).
error(function(status) {
//your code when fails
});
}]);
I've read this may have something to do with my server configuration, I'm using gulp-connect https://www.npmjs.com/package/gulp-connect. Or is it to do with the server config of the site I'm requesting from?
UPDATE
I checked the http headers with curl but it doesn't seem to tell me much?
$ curl -I http://example.com/data.service/getSomething/hghfg7igb757
HTTP/1.1 200 OK
Date: Wed, 07 Dec 2016 22:35:19 GMT
Server: WildFly/8
Expires: Wed, 07 Dec 2016 22:40:19 GMT
X-Powered-By: Undertow/1
X-dmg-elapsed-time: 30ms
X-dmg-host-address: 17?.??.???.?0
X-dmg-generated-time: Wed, 07 Dec 2016 22:35:19 GMT
Content-Type: application/json;charset=UTF-8
Content-Language: en-
X-dmg-node-name: dbfr_node_1
Vary: Accept-Encoding
X-Varnish-Bereq-Backend: real_backend_llr
X-Varnish-Bereq-Retries: 0
Last-Modified: Wed, 07 Dec 2016 22:35:19 GMT
Cache-Control: public, max-age=300
X-Varnish: 1376270
Age: 0
Via: 1.1 varnish-v4
X-Varnish-Cache: MISS
X-Varnish-Served-By-Host: jul.max.ie
X-Varnish-Served-By-IP: 1?.???.??.??
X-Varnish-Pool: http_pages
X-Varnish-Req-Backend-Hint: dead
X-Varnish-Req-Restarts: 0
X-Varnish-Hash: /data.service/getSomething/hghfg7igb757
X-Varnish-Backend-Ourself: varnish_server_jul_llr
X-DMG-Version: 6.20.51.2358
Accept-Ranges: none
Connection: keep-alive
How can I enable CORS with gulp-connect?
install cors package:
npm install --save-dev cors
then add it as middleware to connect:
var gulp = require('gulp');
var connect = require('gulp-connect');
var cors = require('cors');
gulp.task('connect', function() {
connect.server({
root: 'app',
middleware: function() {
return [cors()];
}
});
});
-- https://github.com/AveVlad/gulp-connect/issues/100#issuecomment-74369427
how can I check the headers in the response?
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
});
$http's deprecated custom callback methods - success() and error() - have been removed. You can use the standard then()/catch() promise methods instead, but note that the method signatures and return values are different.
-- AngularJS Developer Guide - Migrating from 1.5 to 1.6 - $http
This turned out to be a CORs issue on the server side
Im trying to get the cookie value from the header but it returns undefined.
Using $cookies module.
Service:
socialMarkt.factory('homeService', ['$http', function($http){
var apiAddress = "http://server.apigoeshere.io:8000/s/first/";
return {
getEvents : function(params) {
return $http.get(apiAddress, {params});
}
}
}]);
Controller:
homeService.getEvents({"page":"1"}).then(
function(response){
$scope.events = response.data.events;
console.log($cookies.get('csrftoken')) //undefined;
});
Response Header
HTTP/1.1 200 OK
Server: gunicorn/19.4.5
Date: Tue, 01 Mar 2016 22:47:55 GMT
Connection: close
Transfer-Encoding: chunked
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Set-Cookie: csrftoken=HN8Zqh7dup4DnnZInd25WT25DEQ3m5rM; expires=Tue, 28-Feb-2017 22:47:55 GMT; Max-Age=31449600; Path=/
Set-Cookie: sessionid=39aq2f5d06ianw65vgm3hmf37ctlbj3l; expires=Tue, 15-Mar-2016 22:47:55 GMT; httponly; Max-Age=1209600; Path=/
I cant get the csrftoken cookie. so i can use it to send post request on a django endpoint.
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?
I am developing a frontend application in AngularJS, an i'am trying to login in a elgg platform.
As described in the documentation here if you want to use HMAC auth, you have to add some custom headers. And in AngularJS I have used interceptors.
$httpProvider.interceptors.push(function($q, HMAC){
return {
// optional method
'request': function(config) {
// do something on success
console.log("Interceptor Config-> ",config);
console.log("HTTP? --> ",config.url.indexOf('http'));
if(config.url.indexOf('http') == 0){
//do something only on http requests
config.headers = config.headers || {};
config.headers['X-Elgg-apikey'] = "";
config.headers['X-Elgg-time'] = "";
config.headers['X-Elgg-none'] = "";
config.headers['X-Elgg-hmac'] = "";
config.headers['X-Elgg-hmac-algo'] = "";
}
console.log("Return -->", config);
return config || $q.when(config);
}
};
});
But the response the response i got is :
XMLHttpRequest cannot load http://localhost/elgg-1.9.8/elgg-1.9.8/services/api/rest/xml/?method=auth.gettoken.
Request header field X- Elgg-hmac-algo is not allowed by Access-Control-Allow-Headers.
I have apache on my webserver on localhost and i have configured :
<Directory />
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Request-Headers "*"
Header always set Access-Control-Request-Method "*"
AllowOverride none
Require all denied
</Directory>
I have also checked the response header and this what i got :
HTTP/1.1 200 OK
Date: Sat, 30 May 2015 13:37:07 GMT
Server: Apache/2.4.10 (Unix) OpenSSL/1.0.1j PHP/5.6.3 mod_perl/2.0.8-dev Perl/v5.16.3
Access-Control-Allow-Origin: *
Access-Control-Request-Headers: *
Access-Control-Request-Method: *
X-Powered-By: PHP/5.6.3
Cache-Control: no-cache, must-revalidate
Expires: Fri, 05 Feb 1982 00:00:00 -0500
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 81
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
I can't find where is the bug. I setted the headers response on the server but i still got this error on console.
Thanks
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