Http Post request is not getting successful in angular js(1.5) - angularjs

I am working on HTTP post request in angular JS (1.5).
First I pass request data to factory method. Call the Http post request and send the response back to controller. But I always get the below error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Below is my controller code:
app.controller("logicCtrl",['$scope','getDestinationService','getVehicleService','getTokenService','getResultService','$http',
function($scope, getDestinationService,getVehicleService,getTokenService,getResultService,$http){
$scope.getResult = function(){
var resultPromise = getResultService.getFinalResult($scope.request_data);
resultPromise.then(function(result){
$scope.result = result.data;
console.log("result:"+$scope.result);
});
}
});
And this is my factory method:
app.factory("getResultService",['$http','$q',function($http, $q){
var getResultApi = "https://findfalcone.herokuapp.com/find";
var headers = {'Accept' : 'application/json'};
var getFinalResult = function(request_data){
var deferred = $q.defer();
var request_data = JSON.stringify(request_data);
return $http({
url: getResultApi,
method: "POST",
data: request_data,
headers: {'Accept' : 'application/x-www-form-urlencoded'}
}).then(function (response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
}).catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
};
return { getFinalResult: getFinalResult };
}]);
Edit: As some people are directly hitting the URL in browser and saying URL is not working. It won't work this way as it is post call, not get call. I tried testing this URL in Postman and it is working absolutely fine.
Here is the screenshot:

In the getFinalResult you are overwriting the Accept header as application/x-www-form-urlencoded where as it should be application/json. You are not using the headers variables declared earlier.
Disclaimer: I wrote the Finding Falcone backend application.

Related

$http return response - AngularJS

I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?

$http get dosn't work frome code but works with other rest client

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;
});

$http - null plain text response

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.

$http Post to php backend, but the server side gets nothing

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

AngularJS withCredentials

I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.
I was able to fix this in jQuery by setting withCredentials to true.
$("#login").click(function() {
$.ajax({
url: "http://localhost:8080/api/login",
data : '{"identifier" : "admin", "password" : "admin"}',
contentType : 'application/json',
type : 'POST',
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
})
});
$("#check").click(function() {
$.ajax({
url: "http://localhost:8080/api/ping",
method: "GET",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
}
})
});
The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:
$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
success(function(data) {
$location.path('/');
console.log(data);
}).
error(function(data, error) {
console.log(error);
});
Can anyone tell me what I'm doing wrong?
You should pass a configuration object, like so
$http.post(url, {withCredentials: true, ...})
or in older versions:
$http({withCredentials: true, ...}).post(...)
See also your other question.
In your app config function add this :
$httpProvider.defaults.withCredentials = true;
It will append this header for all your requests.
Dont forget to inject $httpProvider
EDIT : 2015-07-29
Here is another solution :
HttpIntercepter can be used for adding common headers as well as common parameters.
Add this in your config :
$httpProvider.interceptors.push('UtimfHttpIntercepter');
and create factory with name UtimfHttpIntercepter
angular.module('utimf.services', [])
.factory('UtimfHttpIntercepter', UtimfHttpIntercepter)
UtimfHttpIntercepter.$inject = ['$q'];
function UtimfHttpIntercepter($q) {
var authFactory = {};
var _request = function (config) {
config.headers = config.headers || {}; // change/add hearders
config.data = config.data || {}; // change/add post data
config.params = config.params || {}; //change/add querystring params
return config || $q.when(config);
}
var _requestError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
var _response = function(response){
// handle your response
return response || $q.when(response);
}
var _responseError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
authFactory.request = _request;
authFactory.requestError = _requestError;
authFactory.response = _response;
authFactory.responseError = _responseError;
return authFactory;
}
Clarification:
$http.post(url, {withCredentials: true, ...})
should be
$http.post(url, data, {withCredentials: true, ...})
as per https://docs.angularjs.org/api/ng/service/$http

Resources