Restservice call returns 404 - angularjs

I am making a http.get call in angular js which returns a json file hosted locally.
Scenario:1 -- Success
$http.get("/SuccessResponse.json").success(function(jsonDataa) {
//some code
}).error(function (data, status, headers, config) {
alert("error::"+status);
return status;
});
The above code works perfectly fine and my code inside success gets executed alright.
Scenario : 2 -- Failure
However, when I host the same json on a URI, the http.get call returns 404 and alerts "error::404".
$http.get("http://`10.23.67.43:8080/Api/util`").success(function(jsonDataa) {
//some code
}).error(function (data, status, headers, config) {
alert("error::"+status);
return status;
});
Pls note when I hit the above url on my browser, it displays the JSON perfectly alright. It is only when I try to access it through rest call, it returns 404.
Scenario : 3 -- Success
Also, if I use a public URI (e.g. http://rest-service.guides.spring.io/greeting) it again works alright.
$http.get("http://rest-service.guides.spring.io/greeting").success(..
Can someone pls help in pointing out what's the issue over here?

It's a bit difficult to distinguish how it looks when you are mixing text and markup in your codetags.
However could it be so simple that you use ` in your url?

Related

Read form data in Header in network tab

We are using AngularJs for integrating with PaymentGateway. Success or failure URLs are redirected from PG if it is success/Failure. But in success/failure URL they are posting data about transactions. we have the code to decrypt response message. But i need the code to retrieve the particular form data in value in url encoded.
Please refer below image. i need to fetch highlighted parameter value.
Can anyone help me on this. Thanks in advance
ScreenShot
Could u please try below code.Check is that coming in console.
.success(function(data, status, headers, config) {
console.log(headers); //for success
})
.error(function(data, status, headers, config) {
console.log(headers); //for failure/error
});

403 Error during http request using angular (post)

I made a form with angularJS validation and my code is working fine in localhost. When I try to upload my whole code on my web server, I encounter a 403 Error ( Forbidden ) on line 72 of my angular.min.js file.
I tried A LOT of solutions and I am stuck on this problem.
Here is what I have in my javascript file, the problem seems to come from my server or there as I don't even get into my insert.new.php file due to this 403 error.
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.titles = [];
$scope.SignUp = function() {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$scope.titles.splice(0, $scope.titles.length);
$http.post('insert.new.php', { 'uname': $scope.username, 'email': $scope.useremail }).success(function(data, status, headers, config) {
if (data.msg != '') {
$scope.titles.push(data.title);
$scope.msgs.push(data.msg);
sendContactForm();
} else {
$scope.titles.push(data.title);
$scope.errors.push(data.error);
sendContactForm();
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.titles.push(data.title);
$scope.errors.push(status);
sendContactForm();
});
}
}
I tried to put a .htaccess at the root of my website, the file contains
Order Allow,Deny
Allow from all
I didn't change anything on my webserver itself, it has a "firewall" that i tried to disable in case it could help, but that didn't solve anything.
Using AngularJS 1.2.3 (this version is the highest version that works with this code)
When I submit, in the "source" tab of chrome I get :
angular.min.js:72 POST http://domain.com/insert.new.php 403 (Forbidden)
angular.min.js:72 XHR finished loading: POST
"http://domain.com/insert.new.php".
I think there is a big chance that it has something to do with apache / the configuration of my server, but I cant solve it and nothing that I found until now did help me.
I just solved my problem on puting an .htaccess in all of my documents, one at the root wasn't enough, so problem solved !

Why isn't my AngularJS post receiving data from the server?

I am posting to the server using the following in AngularJS:
$http.post('/myurl', {my: "data"}, function(data, status, headers, config) {
console.log("returned");
});
In Chrome Developer Tools, the server is sending back a 200 OK status message. However, my callback is never triggered (i.e. nothing printing to the console). Why is AngularJS not printing the message even though the server returns OK?
I've not seen request written like that, generally you want to do something like:
$http.post('/myurl', {my: "data"})
.success(function(data) {
console.log("returned");
});
or
$http.post('/myurl', {my: "data"})
.then(function(data) {
console.log("returned");
});
you can try
return $http({url: '/myurl' , method: "POST",data:my});
you can also click on F12 chrome console to see the exact error
in order to serr the results data you can add
$http({url: '/myurl' , method: "POST",data:my}).then(
function(result){
console.log(result);
}

angularjs custom REST action and error handling

I'm having some trouble with error handling in a little angularjs application. I'm interacting with a Flask backend and a Postgres DB.
I have a factory service
appointServices.factory('Appointments', ['$resource', function($resource){
return $resource(someUrl, {}, {
query: { ... }
,
create: {
method: 'POST'
,url: 'http://somedomain:port/new/:name/:start/:end/:treatment'
,params: { start: '#start', end: '#end', name: '#name', treatment: '#treatment' }
,isArray:false
}
});
}
]);
Inside a controller I'm making the following call
Appointments.create($scope.appointment, function(value, responseHeaders) {
// success handler
console.debug('success: ', JSON.stringify(value));
}, function(httpResponse) {
// error handler
console.debug('error: ', JSON.stringify(httpResponse));
});
Here $scope.appointment contains the relevant parameters for the create action.
Now, in the backend I'm able to catch DB errors involving constraints and I'm trying to return an error code with a 'meaningful' message. So I have a python method
def create(name, start, end, treatment):
try:
...
transaction_status = 'ok'
code = 200
except IntegrityError as e:
...
transaction_status = 'IntegrityError'
code = 500
finally:
...
return make_response(transaction_status, code)
Everything works fine, I'm able to talk to the backend, create new data and insert this in the DB. As I said, any violation of the constraints is detected and the backend responds
curl -X POST "http://somedomain:port/new/foo/bar/baz/qux" -v
...
< HTTP/1.0 500 INTERNAL SERVER ERROR
...
IntegrityError
So, the problem is, no matter whether the action create was successful or not, the intended error handler specified inside the controller is always fired. Moreover, I always end up with a status code 404 in the httpResponse. Firebug shows correctly the code 500 as above, though.
Anybody has any idea of why I'm getting this behavior?
Any suggestions on how to improve the error handling mechanism are also welcome.
Thx in advance.
P.S. Following the documentation on $resource I have also tried variations on the factory service call, e.g.
Appointments.create({}, $scope.appointment, successCallback, errorCallback);
Appointments.create($scope.appointment, {}, successCallback, errorCallback);
with the same results.
Update:
Forgot to mention the important fact that I'm interacting with the backend via CORS requests. The POST request in create above is having place with the OPTIONS method instead. As I mentioned everything is working correctly except for the error response.
Under further investigation, I tried to isolate the factory service, in case I did something wrong, and I also tried the approach shown in the credit card example ($resource docs), but with no positive result.
However, I came up with two workarounds. Firstly, I was able to create a plain JQuery POST request, as in the example shown in the docs. This time, the request is not replaced by OPTIONS and I got the error code correctly.
I also managed to connect to the backend with the low-level $http service as follows:
var urlBase = 'http://somedomain:port/new/:name/:start/:end/:treatment';
var url = urlBase.replace(/:name/g, $scope.appointment.name);
url = url.replace(/:start/g, $scope.appointment.start);
url = url.replace(/:end/g, $scope.appointment.end);
url = url.replace(/:treatment/g, $scope.appointment.treatment);
// force method to be POST
var futureResponse = $http({ method: 'POST', url: url });
futureResponse.success(function (data, status, headers, config) {
console.debug('success: ', JSON.stringify(data));
});
futureResponse.error(function (data, status, headers, config) {
console.group('Error');
console.debug(JSON.stringify(status));
console.debug(JSON.stringify(data));
console.groupEnd();
});
This time, as in the case of JQuery, the request is done effectively with POST and error codes are correctly received.
Notice also that I'm not calling $http.post but I set the method to POST as part of the object parameter to $http, otherwise the connection takes places with OPTIONS as before.
Still trying to figure out what is happening with $resource.

angularjs $http.jsonp goes to .error instead of .success even when 200 is received

I'm building an AngularJS app which calls a NodeJS server that gets data from a DB.
The NodeJS returns a JSON.stringify(someArrayWithData).
Here is the AngularJS code:
$scope.getMainGroups = function(){
$http.jsonp("http://127.0.0.1:3000/get/MainGroups?callback=JSON_CALLBACK").success(function(data, status, headers, config) {
$scope.MainGroups = data;
}).error(function(data, status, headers, config) {
$scope.MainGroups = status;
});
};
$scope.MainGroups is going to the .error instead to the success even when I can see in the chrome debugger that the result came back (200 ok).
What am I missing?
You must return a valid JSON response on the server side. The 200 OK is just the GET request that is injected into the DOM. I bet you are not returning a valid JSON response from the server with right response code.
Here is an example on how to construct the response on the server side (PHP):
Simple jQuery, PHP and JSONP example?
As answered here you need to change the NodeJS response. The JSONP answer needs to start with the exact text that AngularJS added in the URL (for example 'angular.callbacks._1').
// changes in your server script used by NodeJS
// Required for JSONP calls, 'callback' matches the '?callback=JSON_CALLBACK'
app.set('jsonp callback name', 'callback');
// ... in your response change json to jsonp
res.jsonp(votes);
After doing these changes, when the server detects a 'callback' in the parameters, answers like this:
/**/ typeof angular.callbacks._1 === 'function' &&
angular.callbacks._1([{"votes":3,"title":"new topic", etc...
Now yes, AngularJS correctly calls back the 'success' function.

Resources