I'm having trouble getting responses from certain sites using http.get. Every get I do from Firebase seems to work, but many other sites do not, although the requests work fine from my browser or curl. I have two URL's that provide the exact same data, one from Firebase and another from a Cloud9 project. The Firebase one works and the c9 one doesn't.
When it doesn't work I get the following response:
{"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://dl-celeb-dp-x2jroy.c9users.io:8081/getScoreboard","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}
I've tried HTTP as well as HTTPS for the one that isn't working but I get the same response either way.
I have a fiddle to demonstrate:
https://jsfiddle.net/9d7mysns/
HTML:
<h1>{{result}}</h1>
<p>{{content}}</p>
</div>
Javascript:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("https://blazing-torch-1276.firebaseio.com/getScoreboard.json") //Working
//$http.get("https://dl-celeb-dp-x2jroy.c9users.io:8081/getScoreboard") //Not Working
.then(function(response) {
$scope.result = "Success";
$scope.content = response;
}, function(response) {
$scope.result = "Error";
$scope.content = response;
});
});
Please help,
Thanks!
I think the second one is not allowing Cross-Domain request. This is what I see in the Chrome console for your fiddle.
XMLHttpRequest cannot load https://dl-celeb-dp-x2jroy.c9users.io:8081/getScoreboard. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.
Try this:
var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', '$http', function($scope, $http) {
//$http.get("https://blazing-torch-1276.firebaseio.com/getScoreboard.json") //Working
$http.get('https://dl-celeb-dp-x2jroy.c9users.io:8081/getScoreboard',{
header : {'Content-Type' : 'application/json; charset=UTF-8'}
}) //Now Working
.success(function(response) {
$scope.result = "Success";
$scope.content = response;
}).error(function(response) {
$scope.result = "Error";
$scope.content = response;
});
}]);
Related
I'm writing a website which uses ngRoute for changing pages.
for logging in a form will appear and when it's successful controller changes the http header for requests in the next steps.
bud the problem is that when I change the header, page should be reloaded if not, the Token would not be added to header.
Controller :
app.controller('catCtrl',['Api','$scope','$cookieStore','$rootScope',function (Api,$scope,$cookieStore,$rootScope) {
$scope.Login = function(){
Api.loginEmail($scope.log_email, $scope.pass, 'chrome', 'windows','').success(function(response){
$cookieStore.put('Auth-Key', 'Token ' + response.token);
$scope.is_Loggedin = true;
$scope.showLoginWin();
}).error(function(response){
$scope.log_email = null;
$scope.pass = null;
$scope.error = response.error;
});
};
}
App.run :
app.run(['$cookieStore','$http',function($cookieStore, $http){
$http.defaults.headers.common['Authorization'] = $cookieStore.get('Auth-Key');
}]);
How can I change the header without reloading page.
so you want to add your token on further request after login.
You can try angular interceptor. Here is few Answers related how to add toke via interceptor.
Interceptor Example 1
Interceptor example 2
sample Code:
app.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['Authorization'] = $cookieStore.get('Auth-Key');
return config;
}
};
});
In your service layer, Ignore verification this header for Login.
Im writing my first app with Angular and now faced up with the problem... I have address for POST request with authentication token. Something like:
http://example.com/orders?authentication_token=123456
So I need to make ng-submit or ng-click that send that request and get a bunch of items and show them on the page...
Also, I have a body for them:
{
"order": {
"seller_id":84,
"price":123,
"delivary_date":"12-12-2025",
}
}
So, what the best way to do that?
So you will have to make one angular service which would communicate with server and fetch the data and one angular controller which will interact with service to get the data and display over the UI.
Lets say service name is MyService:
app.service('MyService', function($http) {
var params = {}; // some parameters
this.getData = function(successCallback, failureCallback) {
$http.post("URL", params).then(function(data) {
successCallback(data);
}, function(data, status) {
failureCallback(data, status);
});
}
});
Controller name is MyCntrl:
app.controller('MyCntrl', function($scope, MyService) {
function successCallback(data) {
$scope.itemList = data;
}
function failureCallback(data, status) {
$scope.itemList = {};
}
$scope.handleClick = function() {
MyService.getData(successCallback, failureCallback);
}
});
I believe it would help you to resolve your requirement!!!
Assume you have a orderCtrl. ng-click or ng-submit is based on your app requirement. Call the function someFunction() that triggers $http post and you can handle the success and failure response.
app.controller('orderCtrl', function($scope, $http) {
$scope.someFunction = function(){
var data = {}; // prepare your data here.
$http({
method : "POST",
url : "specify your url here",
data : data
}).then(function mySucces(response) {
var response = response.data;
// handle your success here
}, function myError(response) {
// handle the failure here
});
});
});
Note :
If you are using a form and you want to trigger this function after user filling all the information, then use ng-submit. If it is independent then use ng-click.
I'm saying again, it's all depends on what you are doing.
I'm using angular to post a form, I'm receiving the following error which is usually related to a get instead of a post, the problem is I've clearly told it to post. Any idea what the issue could be?
An Error Was Encountered
The URI you submitted has disallowed characters.
This is everything related to Angular and the form.
var app = angular.module("scd",
['ngSanitize','ngMessages','angularUtils.directives.dirPagination']);
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.controller('formController', ['$scope', '$http', function($scope, $http) {
$scope.submitEmail = function()
{
$http.post('/learnmore', {data: $scope.learn_more_email});
}
$scope.submitContact = function()
{
$http.post('/contact', {data: $scope.contact});
}
}]);
Learning angular and in my app I have a local json file that I can use $http.get to read data from the file, but now I also want to post data to it.
For example my json file looks like this:
{
"name": "old name"
}
And in my controller I am attempting to edit that name:
var data = $.param(
{"name": "new data"}
);
$http.post('testData.json', data)
.success(function (data,status) {
console.log("Post success");
})
.error(function () {
console.log("Post failed");
});
The error "no element found" appears in my browser console when it attempts the http.post. I'm sure it's pointing to the right file and that the json file is actually there.
Any advice?
Dont forget to stringy the JSON!:
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: "new data"
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
}
})
You cannot post to a local json file -- it just doesn't work that way. This is what you did in your code; see below.
$http.post('testData.json', data)
.success(function (data,status) {
console.log("Post success");
})
As noted, you posted to a local JSON file which -- as stated, just doesn't work.
You need to post to a local endpoint. See #jdersen's comment on the OP for using a https://postb.in/ to post your data OR set up or a local endpoint and try posting to that.
Working Fiddle
My $http functions can return the following errors:
POST http://foobar.dev/foobar 500 (Internal Server Error)
POST http://foobar.dev/foobar 401 (Unauthorized)
Isn't there a way I can catch all status codes?
$http.post('/foobar', form)
.success(function(data, status, headers, config) {
console.info(data);
})
.error(function(data, status, headers, config) {
console.error(data);
if(status === 401) {
$scope.setTemplate('show-login');
}
if(status === 500) {
$scope.setTemplate('server-error');
}
}
);
Where $scope.setTemplate() is a function inside the Controller that sets a view.
But then I have to do this for each error() function and there are a lot functions like this which also not making it DRY code :P
What I want is to catch the error and do an action based on the status code returned in the error.
FYI: I'm not using Angulars $routeProvider().
You can use the Angular $http interceptor for this like #Dalorzo explained:
var myApp = angular.module("myApp", [], ['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$rootScope', '$q', function($rootScope, $q) {
return {
'responseError': function(response) {
var status = response.status;
// Skip for response with code 422 (as asked in the comment)
if (status != 422) {
var routes = {'401': 'show-login', '500': 'server-error'};
$rootScope.$broadcast("ajaxError", {template: routes[status]});
}
return $q.reject(response);
}
};
}]);
});
Then receive it in your controller:
$scope.$on("ajaxError", function(e, data) {
$scope.setTemplate(data.template);
});
Now, you don't have to put in your each error function.
How about something like this instead:
var routes = {'401':'show-login', '500': 'server-error'};
$scope.setTemplate(routes[status]);
Where routes is a dictionary with your error codes and desired routing.
This is exactly what $http interceptors are for. See the interceptors section here: $http
Basically, you create common functionality for all $http requests, in which you can handle different statuses. For example:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2){
return {
response: function(response){
// do something for particular error codes
if(response.status === 500){
// do what you want here
}
return response;
}
};
});
// add the interceptor to the stack
$httpProvider.interceptors.push('myHttpInterceptor');
What I would say initially is to create a decorator for the $http service or create a service that would serve as a wrapper for the $http service.