Angularjs $http.post - sending params as JSON to ASPX webmethod - javascript

I have the following angularjs code sending http post to a webmethod, but I get the following error with no more info. Can someone help?
If I do not send any data to webmethod and only get data from it, it works just fine !
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
angular.js:11442 POST http://localhost:54461/GetData.aspx/getData 500 (Internal Server Error)
Javascript:
var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
$scope.retData = {};
var config = {
headers: {
'Content-Type': '"application/json; charset=utf-8";',
'dataType': '"json"'
}
}
$scope.retData.getResult = function (item, event) {
$http.post('GetData.aspx/getData', request, config)
.success(function (data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
ASPX webmethod (C#):
public static string getData(string name, int age)
{
string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}
EDIT --------------------------------------
If I do not send any json data to the webmethod, it works just fine. for example the below code works and if I put break point inside the webmethod, it shows that it goes there. but if I send json data, it does not go inside webmethod:
Javaacript (not sending any json data):
var config = {
headers: {
'Content-Type': '"application/json; charset=utf-8";',
'dataType': '"json"'
}
}
$scope.retData.getResult = function(item, event) {
$http.post('GetData.aspx/getData', data, config)
.success(function(data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});
}
ASPX (When no input param)
public static string getData()
{
// just having a breakpoint shows it comes inside the
// webmethod when no data is passed.
}

your issue seems to be as pointed by Emmanual Durai in first comment of your question: var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}"; is not a valid json object.
request will give you {'name':'Nariman'age':'12'} as String which won't parse to JSON (there are issues with format).
You should try something like below to get a valid string
var request = {
name: "Nariman",
age: 12
}
var requestString = JSON.stringify(request)
also please have a look here How to pass json POST data to Web API method as object. your issue is not typically specific to angularjs $http but in general to XHR request.

Simply change:
var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
To:
var request = { name: "Nariman", age: 12 };
You don't have to use JSON.stringify()
var request = { name: "Nariman", age: 12 };
var config = {
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}
$http.post('GetData.aspx/getData', request, config)
.success(function(data, status, headers, config) {
$scope.retData.result = data.d;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});

Related

http.post always entering error callback in IE8

I have a simple Angular service that works fine in FireFox, Safari, Chrome and IE9+
However, for IE8, the service is always hitting the .error callback.
JS:
myService.authUser($scope.data)
.success(function(data, status, headers, config) {
console.log("Success..");
$scope.showProfile = true;
})
.error(function (data, status, headers, config) {
console.log("ERRROR!!!");
$scope.errorText = true;
})
app.service('myService', function($http) {
this.authUser = function (myData) {
return $http({
url: 'url',
method: "POST",
data: angular.toJson(myData),
headers: {
'Content-Type': 'application/json'
}
});
};
});
In the above scenario, IE8 is always logging ERRROR!!!
Make sure that the url you are hitting responds with the correct status code EG : 200, 404 etc
For example if your backend is .NET MVC
public ActionResult TestError(string id) // id = error code{
Response.StatusCode = 400; // Replace .AddHeader
var error = new Error(); // Create class Error() w/ prop
error.ErrorID = 123;
error.Level = 2;
error.Message = "You broke the Internet!";
return Json(error, JsonRequestBehavior.AllowGet);}

Download CloudBlockBlob as savable file to a browser from .Net MVC 6

I'm trying to provide a browser user the ability to select a file from a list an download a file back to the user as a file download.
My JavaScript looks like this:
$scope.getFile = function (podUri, podName) {
$http.get('api/getDharmaPod', { params: { containerName: $scope.selectedContainer, podName: podName } })
.success(function (data, status, headers, config) {
$("#audio").text("Got file: ");
})
.error(function (data, status, headers, config) {
alert("got an error:" + status);
});
};
I've also tried the following that I found on stackOverflow
$scope.getFile = function (podUri, podName) {
$http({
method: 'GET',
params: { containerName: $scope.selectedContainer, podName: podName },
cache: false,
url: 'api/getDharmaPod',
headers: {
'Content-Type': 'audio/mpeg; charset=utf-8'
}
}).success(function (data, status) {
console.log(status);
}).error(function (data, status) {
alert("got an error:" + status);
});
};
But the result is the same: the browser silently receives the server's transmission and doesn't offer to save it anywhere.
My MVC controller method looks like this:
[HttpGet, Route("api/getDharmaPod")]
public async Task<HttpResponse> GetDharmaPod(string containerName, string podName)
{
var dharmaBlob = AzureStorageAccess.GetBlob(containerName, podName);
MemoryStream memStream = new MemoryStream();
dharmaBlob.DownloadToStream(memStream);
Response.ContentType = "audio/mpeg";
await Response.SendAsync(memStream.ToArray());
return null;
}
I've also tried:
[HttpGet, Route("api/getDharmaPod")]
public FileResult GetDharmaPod(string containerName, string podName)
{
var dharmaBlob = AzureStorageAccess.GetBlob(containerName, podName);
MemoryStream memStream = new MemoryStream();
dharmaBlob.DownloadToStream(memStream);
Response.ContentType = "audio/mpeg";
return File(memStream.ToArray(), "audio/mpeg", podName);
}
Again the browser receives the data but doesn't see it as a file to be stored. It just receives it into a variable. I'd want it to see it as a download and save it to the download file.
I'm not sure if I'm sending it incorrectly or receiving it incorrectly or both :-(
Thanks for any guidance.
I've decided to go another way since I can't seem to find a solution.
My solution is to just download the file directly from the container using the blob's url. I've made it somewhat secure by generating a shared access key in my controller as follows:
public static string GetSharedAccessKey(string containerName)
{
CloudStorageAccount storageAccount = GetAccount(_useDev);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
SharedAccessBlobPolicy blobPolicy = new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
};
return container.GetSharedAccessSignature(blobPolicy);
}
this returns an access key that can be appended to the 'a' tag's href link for the blob file that allows access for one hour.
I'm now getting a file that the browser is storing in the downloads directory as expected.
The result of allowing direct access to the storage account is also more efficient for the server-side app.

Angular, sending json to an API

I am trying to post json to an api and its giving me the following error...
http://www.website.com/getPriceNoAuth?json=[object%20Object] 405 (Method Not Allowed)
This is the json object I am trying to send and its http resuest...
var productAttributes = {
"CostRequirements":[
{
"OriginPostcode":"BR60ND",
"BearerSize":100,
"BandwidthRequired":10,
"ProductCode":"CON-ELA",
"Term":36,
"Quantity":1
},
{
"ProductCode":"CON-ADD-IP4",
"Term":36,
"Quantity":0
},
{
"ProductCode":"CON-ADD-INT",
"Term":36,
"Quantity":0
}
]
}
this.getPrices1 = function () {
return $http.post('http://www.website.com/getPriceNoAuth?json=' + productAttributes ).
success(function(resp){
//log something here.
});
};
Does anyone see what I'm doing wrong? thank you.
$http({
url:'http://myurl.com'
method:'POST',
data:{
'json':productAttributes
}
});
ORRR if you really need to pass the data from the url stringify your json and decode it on server side
$http.post('http://myurl.com?json=' + JSON.stringify(myJson));
You're trying to post the data, but you're putting it in the url like a get parameter. Post data like this:
this.getPrices1 = function () {
return $http.post('http://www.website.com/getPriceNoAuth', {json: productAttributes} ).
success(function(resp){
//log something here.
});
};
The http header are not defined in there.. but by defaults it considers json as the content type:
$http.post('/someUrl', data).success(successCallback);
here you have to call an api, in which we have to sent data using get
method. Just use the following code and that's it. It works for me, hope it
will work for you also.
var dataObject = {
json : productAttributes
};
var responsePromise = $http.get("http://www.website.com/getPriceNoAuth", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
var outputDate=angular.fromJson(dataFromServer);
if(outputDate.status==1)
{
angular.forEach(outputDate.storelist, function(value, key) {
$scope.userstores.push({name:value.StoreName,id:value.StoreID});
});
}
});
responsePromise.error(function(data, status, headers, config) {
console.log("Error in fetching user store call!");
});

Return post data angular

Im trying to receive data posted by Angular:
$scope.add = function() {
$http.post($rootScope.appUrl + '/nao/test', {"data": "fiskapa"})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status) {
//Göra något
});
};
The problem is that fiskapa is not returned:
public function create($data)
{
return new JsonModel(array("data" => $data));
}
Data that is returned: Object { data=[0]}
You can get directly the json post:
$data = json_decode(file_get_contents('php://input'),TRUE);
Please, try this.

Sending JSON using $http cause angular to send text/plain content type

I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
So I wrote the following function, using Angular $http:
$http(
{
method: 'POST',
url: '/api/user/auth/',
data: '{"username":"alex", "password":"alex"}',
})
.success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});
I read in documentation for POST method that Content-Type header will be automatically set to "application/json".
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
This cause my API to not respond properly to this request. How should I manage this content-type?
The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.
myapp.controller("AccountController", function($scope) {
$scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it
$scope.saveAccount = function() {
users.current.put($scope.user, function(response) {
$scope.success.push("Update successful!");
}, function(response) {
$scope.errors.push("An error occurred when saving!");
});
};
}
myapp.factory("users", function($http) {
return {
current: {
put: function(data, success, error) {
return $http.put("/users/current", data).then(function(response) {
success(response);
}, function(response) {
error(response);
});
}
}
};
});
Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:
$http.put("/users/current", data || {}).then(/* ... */);
Try this;
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post('/api/user/auth/', data).success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});

Categories

Resources