Can't get this AngularJs HTTP request to work? - angularjs

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

Related

angularjs http interceptor responseError object

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');
})

How to enable CORS for angularjs project running using gulp serve

I have an Angularjs project. I build it using gulp serve. I,m using ckeditor to uploade a file on remote server and i get this error:
Permission denied to access property "CKEDITOR" on cross-origin object
my gulp server.js file is as below
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) &&
baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS, POST, PUT');
res.setHeader('Access-Control-Allow-Credentials', 'GET,OPTIONS, POST, PUT');
next();
},
routes: routes
};
browserSync.instance = browserSync.init({
startPath: '/',
server: server,
browser: browser,
ghostMode: false
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
connect.server(server);
});
gulp.task('serve:dist', ['build'], function () {
browserSyncInit(conf.paths.dist);
connect.server(server);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
connect.server(server);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
connect.server(server);
});
but "Access-Control-Allow-Origin', '*'" did not set in header and i still get that error!
when page load Http response and request headers are as below:
response headers:
Access-Control-Allow-Origin *
Access-Control-Allow-Headers *
Access-Control-Allow-Methods GET,OPTIONS, POST, PUT
Access-Control-Allow-Credentials true
Accept-Ranges bytes
Cache-Control public, max-age=0
Last-Modified Wed, 11 Oct 2017 05:56:16 GMT
ETag W/"91a-15f0a01475b"
Date Sat, 14 Oct 2017 05:03:02 GMT
Connection keep-alive
request headers :
Host localhost:3000
User-Agent Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/56.0
Accept application/json, text/plain, */*
Accept-Language en-US,en;q=0.5
Accept-Encoding gzip, deflate
Referer http://localhost:3000/
Cookie language=fa; io=qkk4hCbXxaQ78a…FxfKICyH9dwHZOr5m2aJJ89Z0DS2H
Connection keep-alive
If-Modified-Since Wed, 11 Oct 2017 05:56:16 GMT
If-None-Match W/"91a-15f0a01475b"
Thanks :)
I also used CORS Everywhere Firefox add-on. but it did not work

AngularJS Stalled Requests to REST API

I have an AngularJS (1.4) app that relies upon $http.get requests to a REST API.
There are two types of request, one for "Search Results", and one for "View Profile". Sometimes (but not consistently so), the request for "View Profile" is not returned. Checking in the Chrome network tab it's marked as Stalled.
Looking this up it seems maybe I am hitting the Chrome max connections limit - but I don't understand how this can be the case as surely the "connection" is not created again each time an $http.get request is called?
Does anybody have any ideas?
Simplified code below:
app.factory('garageService', function($http,$q) {
var garageService = {};
var url = ''; // CAN'T SHARE
var token = ''; // CAN'T SHARE
var radius = 50;
// GET SEARCH RESULTS
garageService.getList = function(lat,lng) {
var deferred = $q.defer();
if(window.XDomainRequest){
//XDR Version for IE
} else {
$http.get(url+'/'+token+'/list/'+lat+'/'+lng+'/'+radius, { cache: true, timeout: 10000 }).success(function(response){
deferred.resolve(response);
}).error(function(){
deferred.reject();
});
}
return deferred.promise;
}
// GET VIEW PROFILE
garageService.getProfile = function(id) {
var deferred = $q.defer();
if(window.XDomainRequest){
//XDR Version for IE
} else {
$http.get(url+'/'+token+'/get/'+id, { cache: true, timeout: 10000 }).success(function(response){
deferred.resolve(response);
}).error(function(){
deferred.reject();
});
}
return deferred.promise;
}
return garageService;
});
And here are the response headers from a working request:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin: //CAN'T SHARE
Cache-Control:no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Type:application/json
Date:Thu, 31 Dec 2015 10:28:37 GMT
ETag:"1451557717"
Expires:Sun, 19 Nov 1978 05:00:00 GMT
Keep-Alive:timeout=2, max=200
Last-Modified:Thu, 31 Dec 2015 10:28:37 GMT
Server:Apache
Transfer-Encoding:chunked
X-Powered-By:PHP/5.3.3

AngularJS $http date header

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

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