Angular js http.get request not hitting my url - javascript

as i am working on angular js for using the rest-full web services in my website,
but my problem is i am getting controll into error field instead of success and i stucked into it since past three days any help will be appreciated more, and this is my anguls js code.
`
function customersController1($scope, $http) {
$http({
url: 'http://localhost:9090/quote',
dataType: 'text/json',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function(data){
$scope.data = data;
alert(data);
}).error(function(error){
$scope.error = error;
alert('error');
});
}
</script>
`enter code here`<div ng-controller="customersController1">
<!-- div>{{ quotes }}</div-->
<ul>
cc <li ng-repeat="quotes"> cc{{ quotes }}</li>
</ul>
</div>`
thanks in advance friends.

First make sure the url is working by accessing it in browser and then ensure sure you are using ng-app in your html .
Next -
$http's config object doesn't have ant property 'dataType'. you can remove and try your example.
$http(
{
method : 'GET',
url : 'http://localhost:9090/quote',
}
).success( function(data, status, headers, config)
{
})
.error(function(data, status, headers, config)
{
});
or else you can even use $http's get method to for http get calls.
var config = {};
$http.get('http://localhost:9090/quote', config)
.success(function(data, status, headers, config) {})
.error(function(data, status, headers, config) {});
To know more, read - https://docs.angularjs.org/api/ng/service/$http#get
A note - content-type header is usually sent in http request header while making an POST/PUT call to specify the content type sent from client to server. In your case, you may not need the header.
To know more read - http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

Related

Error -1 send parameters using $http.post angular

I have a problem when you submit parameters using $ http.post in angular.
I assume it's some sort of error itself have little knowledge of angular , because in jquery work fine.
Request jquery'javascript
var user = $('#usuariotxt').val();
var pass = $('#passwordtxt').val();
var login= {
Usuario : user,
Password : pass
};
$.ajax({
type: 'POST',
url: 'http://190.109.185.138/Apipedro/api/login',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
Request Angular-Javascript
var app;
app = angular.module('AppUPC',[]);
app.controller('Formulario',['$scope', '$http', function ($scope, $http){
$scope.login = function(){
var login = {
Usuario: $scope.usuariotxt,
Password: $scope.passwordtxt
};
console.log(login);
var url, method;
url = 'http://190.109.185.138/Apipedro/api/login';
method = 'POST';
$http.post("http://190.109.185.138/Apipedro/api/login", {},
{params: {Usuario:$scope.usuariotxt, Password:$scope.passwordtxt}
}).success(function (data, status, headers, config) {
$scope.persons = data;
console.log($scope.persons);
}).error(function (data, status, headers, config) {
$scope.status = status;
console.log($scope.status);
});
};
}]);
I have also used many other forms , including the most common
$http({
url: url,
method: method,
data: login,
headers :{'Content-Type':'application/json'}
})
Errors that occur to me are the following
Short answer: If you want to send the same data as the jQuery example, use this
app.controller('Formulario', ['$scope', '$http', '$httpParamSerializer', function ($scope, $http, $httpParamSerializer) {
// snip
$http.post(url, $httpParamSerializer(login), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function success(response) {
$scope.persons = response.data;
}, function error(response) {
$scope.status = response.status;
});
}]);
This is because jQuery by default sends POST data as an x-www-form-urlencoded string, ie
Usuario=dfvides&Password=dfvids
Using the code above, Angular will send an identical request to jQuery.
Angular by default sends POST data as JSON with the Content-Type header set to application/json, ie
{"Usuario":"dfvides","Password":"dfvids"}
Is your API even set up to handle a JSON payload?
The reason your Angular version was triggering a pre-flight OPTIONS request (which it appears that your API is not equipped to handle) was because the header Content-Type: application/json makes the request non-simple...
A simple cross-site request is one that:
Only uses GET, HEAD or POST. If POST is used to send data to the server, the Content-Type of the data sent to the server with the HTTP POST request is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain.
Does not set custom headers with the HTTP Request (such as X-Modified, etc.)

cordova + angularjs + nodejs(Express) $http json always get 404

I am using cordova + angularjs + nodejs(Express) to test in android environment. Now I am trying to get some data by $http(), but I always get 404 error (by the alert below).
Client Code ( AngularJs )
$http({
method : 'POST',
url : "http://192.168.1.4:8888/login",
data : ""
})
.success(function(data, status, headers, config) {
alert("success");
alert(data);
})
.error(function(data, status, headers, config) {
alert("error");// <== always gets here
alert(status); // <== 404
}).
finally(function() {
alert("finally");
});
Server Code (NodeJs+Express)
...
app.get('/login',function(req, res){
res.set({'Content-Type':'application/json','Encodeing':'utf8'});
res.json({name:"jj"});
}) ;
app.listen(8888);
I can get the json string by visit http://192.168.1.4:8888/login by Chrome,
I searched a lot of stuff but still can't solve my problem, could anyone help?
The http method is post, it needs to be get.

Internal column name reference not working in Sharepoint

I tried to retrieve a lookup column from a list. The list name is "Colors" and the lookup column name is "RedPencilBox:E-Mail"; however, I am getting the "error in controller 2" alert. I wonder if this is because of the length of the internal name of "RedPencilBox:E-Mail"(?).
var module2 = angular.module('App2', []);
module2.controller('Controller2', function ($scope, $http) {
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Colors')/items?$select=Title, Id, RedPencilBox%5Fx003A%5FE%5Fx002d%5FMail/EMail&$expand=RedPencilBox%5Fx003A%5FE%5Fx002d%5FMail/EMail",
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.project = data.d.results;
}).error(function (data, status, headers, config) {
alert("error in Controller2");
});
});
Try your request url right in a browser. It should return an exact error, maybe you'll get a clue.
Also try this url without query parameters: "webURL + /_api/web/lists/getByTitle('Colors')/items" - to see if your field's internal name is exactly the same you have in the query url.
I don't think you need encoding here: just try pass it as it is: RedPencilBox_x003A_E_x002d_Mail
Best regards, Polina

CORS error when POST data in AngularJS & CodeIgniter3

I'm use AngularJS 1.3 and CodeIgniter 3.0.
I success to GET data from php in localhost.
However I have error "Cross-origin-request blocked".
I do not know it but was a search, plese help me.
Javascript
var module = angular.module('app', ['onsen']);
module.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
module.controller('MasterController', function($scope, $http) {
$scope.doLogin = function() {
var postData = {"email": "aaa#bbb.ccc", "password": "pass"};
var url = 'http://example/test?callback=JSON_CALLBACK';
//This section is Error
$http.post(url, postData, {withCredentials: true})
.success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
//This section is Success
$http.get(url).success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
};
});
I tried "$http({url ~})", but It was the same result.
PHP
public function index() {
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$this->output
->set_header("Access-Control-Allow-Origin: *")
->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin")
->set_content_type('application/json')
->set_output(json_encode($input_data));
}
Try Using .htaccess to allow CORS. Put this in your server .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Even accessing different port is perceived by browser as cross-domain action, the best guide so far how to enable CORS can be found here http://enable-cors.org/

Angular doesn't update my object after http request

this is my angular code:
samirsoftApp.controller("OrderCtrl",function($scope,$http){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.$apply(function(){
$scope.item = data;
});
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
when it request and get answer, it does not update my item object, so I used $apply and it did not work and throw an error:
Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.13/$rootScope/inprog?p0=%24digest
S/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417
.....
I also tried
$timeout(function() {
$scope.item = data;
}, 0);
instead of $apply` but it prints a null object in consol
it's like this:
samirsoftApp.controller("OrderCtrl",function($scope,$http,$timeout){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$timeout(function() {
$scope.item = data;
}, 0);
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
What should I do for my object to be updated after a http request.
thanks
You can assign the data returned by $http.get() request like this
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.item = data;
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data);
});
};
No need for $apply as angular automatically updates $scope
I suspect the problem is elsewhere with your code
Possibly:
You defined function#getItem which contained the $http request but where did you call it?
Make sure the call to URL /test/getItemDetails/ is
returning data by manually browsing or by using a utility like POSTMAN.
being called with the proper URL - try checking in developer tools > network for 404 Errors
I have updated your code - demo here - http://jsbin.com/notudebiso/1/edit?html,js,output
(using a $http call to github api)

Categories

Resources