Making post request to server through angularjs getting error 404 - angularjs

.controller("HttpPostController", function ($scope, $http)
{
console.log('SendHttpPostData login', $scope.loginData);
$scope.SendHttpPostData = function ()
{
var data =
{
name:$scope.loginData.username,
pwd:$scope.loginData.password
}
var config =
{
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http.post('demo url', data, config)
.success(function (data, status, headers, config)
{
console.log(" success"+status);
})
.error(function (data, status, header, config)
{
console.log(" error"+status);
});
};
This is my code , I have called function SendHttpPostData() on
ng-submit="SendHttpPostData()" in html file and added ng-controller in div properly than to i am getting 404 error whenever SendHttpPostData() is called,Please help me.

Try this if it may help you. But you haven't defined demo_url.
var demo_url = 'http://facebook.com:8081';//whatever your url is
$http({
method: 'POST', url: demo_url, data: { name:$scope.loginData.username, password: pwd:$scope.loginData.password },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config)
{
console.log(" success"+status);
})
.error(function (data, status, header, config)
{
console.log(" error"+status);
});

Related

onsen ui not working $http in emulate

module.controller('HomeController', function($scope, $http) {
$http.get('http://104.155.209.198/list/json')
.success(function (data) {
$scope.home_items = data;
console.log('call HomeController');
})
.error(function (error) {
$scope.error = "error";
});
$scope.ClickHome = function (url) {
$http.get('http://104.155.209.198'+url+'/json')
.success(function (data) {
$scope.list_items = data;
console.log($scope.list_items);
console.log('call ListItems');
});
};
$scope.ClickList = function (url) {
$http.get('http://104.155.209.198'+'/list'+url+'/json')
.success(function (data) {
$scope.viewObject = data;
console.log($scope.viewObject);
console.log('call ViewItems');
})
};
});
This is my Angular code. This work in WebBrowers but not working in ios-emulate. what is a problem? not working $http in onsen-ui?
The problem might be loading of external content.
You can inspect the problem with Safari. If that's the case, this might help: http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/
Add this to platforms/ios/<appname>/<appname>-Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
new version of onsen ui not supported $http in emulate android
$http({
method: 'POST',
data: 'Username=' + $scope.user.email + '&Password=' + $scope.user.password + '&is_varified='+$scope.user.is_varified+'&gcm_reg_id='+gcm_reg_id,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: myService.ajax_base_url+'/login/validate_mobile_user'
}).
success(function(data, status, headers, config) {
//console.log(data);
alert('in success');
modal.hide();
}).
error(function(data, status, headers, config) {
modal.hide();
alert('in error');
});

AngularJS - accessing http headers

I am trying to access the http headers in my angular controller but I am getting undefined. Also, I am able to see the header response in my angular service which is not reflecting in my controller. Can someone please tell me what I am missing? Please see the code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
deferred.resolve(data, status, headers, config);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (data, status, headers, config) {
**//getting undefined here.**
$scope.totalRecords = parseInt(headers('X-TotalRowCount'));
$scope.suppliers = data;
}, function (error) {
// error handling here
});
I have found the solution by myself. All I have to do is create an array and add all those values to the same & return it to the controller. Please see the updated code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (response) {
$scope.suppliers = response.data;
$scope.totalRecords = parseInt(response.headers["x-totalrowcount"]);
}, function (error) {
// error handling here
});
This question is old, but $http() returns a promise itself. you can just return that from your service, no need to create a new promise. You can do this even after using .success() and .error(), or for that matter even after using a .then(), they keep chaining.
I had to access Token and TokenExpiry time from response headers of my Rest Service,then store it in my $rootScope.
Here is the code I used:
$scope.Authenticate=function(){
var EncDecUserPass=decodeURIComponent(encodeURIComponent($scope.LoggedUserName+':'+$scope.LoggedUserPassword)) ;
$http(
{method: 'GET',
url: 'http://localhost:53256/api/Products/Authenticate',
cache: false,
headers:{'Authorization':'Basic '+window.btoa(EncDecUserPass)}
}
).success(function(data, status, headers, config) {
//Here it goes
$rootScope.token=headers().token;
$rootScope.tokenExpirySec=headers().tokenexpiry;
}).error(function(data, status, headers, config) {
alert('Invalid User');
});
}

How can I track the start and end of a number of async processes with AngularJS?

I have a loading icon set up on my page that looks like this:
<div class="loading-mask"
data-ng-show="action != null">
<span>{{action}} ...</span>
</div>
When I set $scope.action to a message appears in the loading box.
When loading my page I have a number of different async processes that get data. For example I have:
getUserProfiles: function ($scope) {
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
and:
getSubjects: function ($scope) {
var url = '/api/Subject/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
How can I make it so that the first of these async processes causes a "Loading" message to appear and the last of the async process causes the loading box to not show any more. Note at this time I am not concerned about error messages. I just want the loading to not show when everything is completed.
To expand on what devmiles has said, but to handle the multiple asynchronous functions, you will want to set a loading flag on your first function to be called. I.e.:
getUserProfiles: function ($scope) {
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
And then you will want to wrap each of your asynchronous functions in a promise, like so:
getUserProfiles: function ($scope) {
var deferred = $q.defer();
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
deferred.reject();
});
return deferred;
},
You can then call $q.all on all of your asynchronous functions, and the success callback of this will occur once all asynchronous functions have resolved:
$q.all([getUserProfiles, getSubjects]).then(function() {
$scope.loading = false;
}
This means once all of your functions have resolved, loading will be set to false.
NB: If you want to access the data of your callbacks, you can pass it in as a parameter of "deferred.resolve(x)", and then in your $q.all callback, it will be available as function(x) { do something with x }.
Hope this helps!
EDIT: Don't forget to pass in angular's promise service, $q, to the controller where your functions are.
Just set some boolean flag on when your controller is being instantiated and reset this flag in your success/error functions.
.controller('MyCtrl', function ( $scope ) {
$scope.isLoading = true;
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
$scope.isLoading = false;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
$scope.isLoading = false;
});
});
Use ng-show with this flag to show your loading thingy.

How can I use POST in $http to send an object to the server?

I am using the following:
var url = '/api/Test/Mark';
$http('POST', url, $scope.content.answers)
.success(function (data, status, headers, config) {
$scope.content = data.text;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
This gives me an error when I try to call it:
TypeError: Cannot use 'in' operator to search for '3' in POST
at isArrayLike (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:183:81)
at forEach (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:225:16)
at http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:329:7
at forEach (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:227:18)
at extend (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:327:3)
at $http (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:6256:7)
at Scope.$scope.markQuestion (http://127.0.0.1:81/Content/app/questions/controllers/content.js:39:13)
at elementFns (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:8564:19)
at http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:15511:13
at Scope.$get.Scope.$eval (http://127.0.0.1:81/Scripts/angular-v1.2.0-rc.2.js:10034:28)
Can someone give me advice on what I may be doing wrong? Note $scope.content.answers is an array of data.
You are doing wrong with $http
Try This
var url = '/api/Test/Mark';
$http({
method: 'POST',
url: url
data: $scope.content.answers // this should be a object e.g { a : 'one', b: 'Two' }
})
.success(function (data, status, headers, config) {
$scope.content = data.text;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});

$http post in Angular.js

I've just started learning Angular.js. How do I re-write the following code in Angular.js?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Here's what I have so far -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
html
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Am I in the right direction?
In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.
So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
use $http:
AngularJS: API: $http
$http.post(url, data, [config]);
Implementation example:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
Lets break this down: Url is a little obvious, so we skip that...
data: This is the body content of your postman request
{
Description: 'Test Object',
TestType: 'PostTest'
}
config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});

Resources