Post null value from ionic to asp.net web Api - angularjs

I tried to make a post request from ionic to web api this way
ionic code
$http({
url: 'http://localhost:1449/api/IonicApi',
method: "POST",
data: {
firstName : "a",
lastName : "b",
email : "ab#ab.com"
},
headers: { 'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8" }
}).then(function (response) {
// success
$ionicPopup.alert({
title: 'Your Name is '+$scope.man.firstName + ' '+$scope.man.lastName,
template: 'It might taste good'
})
}, function (response) { // optional
// failed
console.log('failed');
});
and the c# part is
public IHttpActionResult Post(tblPerson person)
{
db = new MobileDBEntities();
db.tblPersons.Add(person);
db.SaveChanges();
return Ok();
I tried from postman to post data it was working. But from Ionic it is passing null data of object
What wrong did I make here?
Postman screenshot I am adding here

Is it possible to call you api like below where obj is your data
$http.post('http://localhost:1449/api/IonicApi',obj).success(function(){
}).error(function()
{
});

Related

AngularJS $http.delete not working in Azure App Service

A follow-up on a similar question I posted yesterday. I am trying to delete data from a table in Azure App service. This is my function in my Angular file.
function delName(user) {
//$scope.categories.push(user);
alert("about to delete. Action cannot be undone. Continue?")
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Then I added an HTML button:
<button id="btn-del-evangelist" class="btn btn-default btn" ng-click="delName(user);">Delete User</button>
This is the value of my headers variable:
var config = {
headers: {
'Access-Control-Allow-Origin':'*',
'ZUMO-API-VERSION': '2.0.0'
}
};
But when I tried to run it, the console returns the following error:
which states that the header for ZUMO-API-VERSION must be specified.
Below is my code for GET and POST
GET:
function getNames() {
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', config)
.then(function (res) {
console.log(res);
$scope.people = res.data;
});
}
POST
function addName(user){
//$scope.categories.push(user);
alert("about to post!")
$http.post('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Since I have already specified the header in my variable, I wonder what can be wrong here. Any help will be appreciated.
UPDATE:
I figured out that the Id must be appended to the URL before I can perform delete. However, I need to run a GET to retrieve the ID given the parameters but I am still encountering errors when getting the ID.
This is now my Delete function
function delName(user) {
alert("About to delete. Action cannot be undone. Continue?")
var retrievedId = "";
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' }
})
.then(function (res) {
retrievedId = res.id;
alert(retrievedId);
});
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + retrievedId, config)
.then(function (res) {
$scope.getNames();
});
}
Does anyone know what is wrong in the GET command when getting the ID?
UPDATE 2: I have written instead an Web Method (asmx) that will connect to SQL server to retrieve the ID passing the needed parameters. The ID will be returned as a string literal but in JSON format. Then I called JSON.parse to parse the string into JSON object then assigned the ID to a variable to which I appended in the URL. –
This is now my Delete function after I have written the Web Method.
function delName(user) {
var confirmres = confirm("You are about to delete this record. Action cannot be undone. Continue?");
var retrievedId = "";
if (confirmres == true) {
//get the ID via web service
$http.get('\\angular\\EvangelistsWebService.asmx/GetId', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' },
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.then(function (res) {
$scope.retData = res.data;
var obj = JSON.parse($scope.retData);
angular.forEach(obj, function (item) {
if (item.length == 0)
alert('No data found');
else {
//perform delete after getting the ID and append it to url
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + item.id, config)
.then(function (res) {
$scope.getNames();
});
alert(item.id + ' deleted');
}
});
});
}
}
That is one way that I have learned on how to call HTTP DELETE on AngularJS. But I don't know if that is the optimal one. In any case, that works for me, unless there will be other suggestions.
$http.delete only has one parameter (config), not two (data, config).
Delete API
delete(url, [config]);
vs.
Post API
post(url, data, [config]);
To your updated problem:
To delete an item from your table, it appears the correct url is:
/tables/tablename/:id
Note the : before id.

Unable to send data to web api methods using angularjs

Hi I am developing one application using web api2 and angularjs. Finding hard time to send data to web api methods. I am having problem to send data as objects n PUT and POST methods. In delete and getbyid methods i am able to send single parameter but i am not able to send data as object. I am receiving null as below.
I am calling as below using angularjs.
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: sub,
url: '/NCT_Users/',
// contentType: "application/json"
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
}
If i comment header and uncomment contentType in above code I am getting totally null object as below.
May i know why i am not able to bind object to model? Any help would be appreciated. Thank you.
var person = {firstName:"John", lastName:"Doe", age:46};
$http.post('url', person)
.success(function (response){
alert(response);
});
accesstoken is defined variable.you can define your variables to pass it to server
var person = {
firstName:"John",
lastName:"Doe",
age:46
};
$http.post('url', person)
.success(function (response) {
alert(response);
});
try this way.
var sub = {
User_CreatedDate: "",
UserEmailId: "",
User_Id: "",
User_MobileNum: "",
User_Name: "",
User_Password: "",
User_Role: "",
User_Status: "",
User_UpdateDate: ""
};
$http.post('/NCT_Users/', sub).success(function (response) { alert(response); });
the fields are filled by you
It happens like this because you are sending an JS Object via an 'application/x-www-form-urlencoded' header. You have to send the data as parameters, try this updated function:
this.saveSubscriber = function (sub) {
return $http({
method: 'POST',
data: $.param(sub),
url: '/NCT_Users/',
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}

req.body is null in expressjs server when sending post request from ionic app

I am developing an ionic app when I am sending a post request using angularjs $http.post to my express js server, I cannot see the data in the req.body.
I am running my server on localhost:3000
Code in my server for CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET,PUT,DELETE,POST");
next();
});
My angular Js post request
$http.post('http://localhost:3000/signup',{"username":"x","password":"y"}).success(function(res){
console.log(res);
if(res.msg=="success")
{
//do something
}
}
I am able to see data in req.body as "key" like:
{'{"username":"x","password":"y"}':''}
When I am setting the header from ionic app as:
$http.defaults.headers.post["Content-Type"] = 'application/x-www-form- urlencoded; charset=UTF-8';
Please let me know how to debug this
You are getting the entire data as key in req.body. This is because the angular request that you are making is wrong. Here is the part of code that should work
$http({
url: 'http://localhost:3000/signup',
method: "POST",
data: { username : "a" , password : "b" }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
Well I figured that out
I have used this stackoverflow link Ionic framework http post request to parse my data before its send to my server
$http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded; charset=UTF-8';
Object.toparams = function ObjecttoParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: 'http://localhost:3000/signup',
method: "POST",
data: Object.toparams(u)
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
});

Angular posts whole data to Django view as key in QueryDict

I am using Angular 1.4.4 and Django 1.8. When i post data from Angular to Django view it comes in the form of whole data as key in the QueryDict.
So in view in debug mode when i evaluate request.POST it returns this
<QueryDict: {u'{"messagetitle":"","value":"","valueam":"","wrong_response":"","stop":"","messagekind":"1","undefined":"","messagetype":"3","state":"","language_id":1}': [u'']}>
Notice posted data is inside u'' as key and its value is [u'']
Angular dataservice code is this
function createDraft(data) {
return $http({
url: view_url + 'create_draft/',
method: 'POST',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
Controller code
app.controller('message',function($scope, $ngBootbox, dataservice, $http){
$scope.formData = {
"messagetitle":"", "value":"", "valueam":"",
"wrong_response": "", "stop": "", "messagekind": "1",
"undefined_response": "", "messagetype":"3",
"state": "", "language_id":1
};
saveDraft = function(){
dataservice.createDraft($scope.formData).then(
function(res) {
$ngBootbox.alert("<div class='alert-success alert_box'>Draft Saved</div>")
},
function(res) {
var error_message = res['statusText'].trim();
if (error_message === '')
error_message = 'Error Occurred';
$ngBootbox.alert("<div class='alert-warning alert_box'>" + error_message + "</div>")
})
}
saveDraft function is called from angular template(which is html form) on button click.
Let me know what i am doing wrong here. I have tried some answers on stackoverflow but could not find any question/answer which addresses my specific problem.
PS:
I know i can do json.loads(request.body) but i need to post data in django's request.POST
Use $.param(data) instead of data in your service

Angular : Error calling WCF service using AngularJS $http

Error while trying to access WCF service using AngularJS $http. Here is the AngularJS code :
$http({
method: 'POST',
url: 'http://localhost:59412/ToDoService.svc/SignIn',
params: JSON.stringify({ username: 'jay' }),
headers: {
"Content-Type": "application/json"
}
})
.then(function (res) {
console.log(res);
})
Here is the WCF web service code (ToDoService.svc.cs) :
public void SignIn(string username)
{
}
ToDoService.svc code is :
[ServiceContract]
public interface IToDoService
{
[OperationContract]
[WebInvoke(Method = "POST")]
void SignIn(string username);
}
The error shown in browser console is :
POST http://localhost:59412/ToDoService.svc/SignIn?0=%7B&1=%22&10=%22&11=:&12=%22&13=j&14=a&15=y&16=%22&17=%7D&2=u&3=s&4=e&5=r&6=n&7=a&8=m&9=e 500 (Internal Server Error)
NOTE: Works fine if I remove the params from the service call.
replace params with data option
data: JSON.stringify({ username: 'jay' })

Resources