I have an $http POST call in AngularJS that won't show the server response if the request was bad.
myFactory.create = function(formData) {
deferred = $q.defer()
$http({method: 'POST', url: url, responseType: 'json', data: formData})
.then(function(data) {
deferred.resolve(data);
}, function(response, status, headers, config) {
deferred.reject(response);
});
return deferred.promise;
};
When I submit incorrect data, the API responds with a 400 - Bad Request. If I look at the response in Chrome Developer tools, there is a plain text message: "Vertical is not correct." However, that message is not in the response on the $http error callback.
I can get everything else (status, headers and config) but my response data is null.
Successful POSTs are processed correctly so I know that the function generally works.
Any idea why I would be able to see the response in Chrome but not able to access it via $http?
You can refactor to this:
myFactory.create = function(formData) {
var url = 'api/create';
return $http({
method: 'POST',
url: url,
responseType: 'json', //Are you sure that it is returning a json??
data: formData
});
};
Then check the return of the promise like this wherever you wish to call it,
myFactory.create().then(
function(data){
console.dir(data);
},function(response, status, headers, config) {
console.dir(response);
});
This should work and you should see the data on the logs.
Related
When I pass JSON data from AngularJS to MVC. I am getting below error.
Http request configuration url must be a string or a $sce trusted object. Received: {"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD":{"Name":"qqq","Address":"www"}}}
MVC code:
[HttpPost]
public JsonResult SavePDDetails(PDDetailsDTO PD)
{
new PDDetailsDAL().SavePDDetails(PD);
return Json(new { Success = true, Message = "Success" });
}
AngularJS code
$scope.Click = function() {
console.log('clicked');
$http.post({
method: 'POST',
url: 'Home/SavePDDetails',
datatype: "json",
data: {
PD: $scope.PD
}
}).success(function(response) {
console.log('success');
console.log(response);
}).error(function(response) {
console.log('error');
console.log(response);
});
}
If data and url are passed as a properties of the config object, don't use the $http.post method. Simply use $http:
̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶{̶
$http({
method: 'POST',
url: 'Home/SavePDDetails',
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
data: {
PD: $scope.PD
}
})
There is no need to stringify the data as the $http Service does that automatically.
Try as follow in your function.
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({PD: $scope.PD});
$http.post('Home/SavePDDetails', parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I have a problem with angular $http get with Authorization header.
I tried to excute the same request with different rest client and response are the same each one.
Advanced Rest Client Chrome extension
Soap-Ui
Insomnia
I have always received the same response with 200 status code.
but when I try to make the same call from my angular application I get 403 status code and response is an OPTIONS.
where I'm wrong?
this is my code:
Config
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Authorization']='Bearer 24ac24e6-0f9b-48b5-923f-b75986226bd9';
});
Service
app.service('DiscoveryService', function ($http) {
this.getData = function (callbackFunc) {
$http({
url: 'https://test.test/test-api/source-monitor/v1/discover',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response);
}).error(function (error) {
console.log(response);
});
};
});
Controller
DiscoveryService.getData(function (dataResponse) {
$scope.data = dataResponse;
});
I am making an angular http post to an API which like this
$http({
method: 'POST',
url: 'http://api/ClientEndpoint',
data: register,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).error(function (data, status, headers, config) {
alert(data);
});
which is returning the following response
But I am not able to store the response path in a variable. How can I do that?
It is cross domain scenario and this is the response being showed in chrome console
I want to access store the ClientEndpoint value
Did you forget the .success(function (data) { }) callback ? just like the .error() you put after the http() function
i hope this will solve your problem ;)
Use the headers variable in either your .succes(response, headers) or .error(response, headers).
E.g :
.success(function(data, status, headers, config) {
//Success Handling
});
.error(function(data, status, headers, config) {
//Error Handeling
});
This only works if you are on the same domain as the server, if it's cross domain, the server has to send the Access-Control-Expose-Headers for you to make this work.
I am trying to send the post request with json data to server. But seems angularJS $http.post method does not set the data into body. How can I make it set the data into body?
The remote server is implemented use asp.net webapi and will read the data from body. so I need to set the json data into request body.
How can I implement this please? Thanks.
If the request send to same site, then it works. But if I send the request to CROS server, it does not work.
In the remote backend server, I already updated the webconfig to make it support CROS call, but it still does not work.
$http.post(resourceUri, requestData)
.success(function (response) {
})
.error(function (data, status, header, config) {
});
You could build the request like this:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': "application/json"
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
YOu can do it as follows
1. make a controller
2. make a add data to the call
syntax for the post call is as follows
$http.post(url, data, [config])
app.controller('controller', function ($scope, $http, $routeParams) {
$http.post('url',data.call1($routeParams.id))
.success(function (response) {
$scope.response = response;
})
.error(function (data, status, headers, config) {
});
});
var data = {
call1:
function (value) {
return {'key': value, 'key': 'some text'};
}
}
I'm learning AngularJS, and trying to post dump data to the php backend using the coding below.
angular.module('app.customerModule', [])
.factory('customerFactory', function($scope, $http) {
return {
var customer = {customer: '1234'};
httpNewCustomer: function(callback) {
$http.post('http://domain.local/customer_new.php', )
.success(function(data) {
})
}
}
})
.controller('customerController', function($rootScope, $scope, customerFactory) {
$scope.newCustomer = function() {
customerFactory.httpNewCustomer(function(dataResponse) {
});
}
});
Unfortunately at the server side gets nothing for $_POST;
This is what the http header looks like.
I also tried with this alternative coding
httpNewCustomers: function(callback) {
var postData = {customer: '2345'};
$http({
method: 'POST',
url: 'http://domain.local/customer_new.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
})
.success(function(data) {
})
}
This is what the http header looks like.
When I tried with jQuery using this coding, everything is just fine.
var postData = {customer: '3456'};
$.ajax({
type: 'POST',
url: 'http://domain.local/customer_new.php',
dataType: 'json',
data: postData,
success: function(data) {
// console.log(data);
}
});
Please help me config the $http to post the data to the php backend.
angular by default only supports a json request transformer. as you can see, both your angular requests have data, but they are json. You either need to change the server so it can parse json, or add a request transformer so the data is in form-encoded format.
You can read more about $http transformers here: https://docs.angularjs.org/api/ng/service/$http