I am new to AngularJS. I have a .net MVC WebAPI Restful app running on a IIS server. When I query the api with http://xxx.xxx.xxx.xxx/api/project I get:
[{"Id":1,"Name":"Glenn Block","Created":"0001-01-01T00:00:00"},{"Id":2,"Name":"Dan Roth","Created":"0001-01-01T00:00:00"}]
I created a ProjectCtrl (in a separate empty project) that looks like this:
angular.module('Project', ['ngResource']);
function ProjectCtrl($scope, $resource) {
$scope.project = $resource('http://192.168.1.221/api/project'
);
$scope.project.get(function (data) {
console.log('success, got data: ', data);
}, function (err) {
alert('request failed');
});
}
I always get a failure. I addressed CORS issues on the server and the request header contains
Access-Control-Request-He... x-requested-with
Access-Control-Request-Me... GET
What I find odd is that when I look in firebug it does NOT do a get but rather shows Option project with a status of 200
I am not sure what I missing.
The error mentioned in your comment, "Error: a.push is not a function", is because your response is an array. With $resource, use the query function when your response is an array.
I think the first parameter of the resource call should be resource-based params. If you have none, pass an empty object {} as the first parameter:
$scope.project.get({},function (data) {
console.log('success, got data: ', data);
}, function (err) {
alert('request failed');
});
My guess is that your err object is actually the successfully returned data. If I'm wrong, tell me and I'll delete!
Related
I have the following AJAX that will send the entered data to the node server and the controller will check whether such data exist in the database or not.
If I do enter the data correctly, then everything is working fine.
However, I tried enter anything that the database does not have and it immediately throw an error, causing the server to stop. The error said that I did not handle the event, so I tried with res.json(err) in the controller instead of throw new Error, hoping that the error will be passed back to AJAX under the error key, but it is still not working. The error still gets thrown and the node server terminate itself.
I would like the server to continue and alert to the user that the data that was entered is not in the database but I have no idea why my approach is not correct.
I was thinking of using this SO thread if I'm able to get the error message back first from server side.
jQuery Ajax error handling, show custom exception messages
To solve the server from stopping, I used the code in app.js that was referred from this link
How do I prevent node.js from crashing? try-catch doesn't work
I'm not sure whether should I use the accepted answer for my case.
function createProduct(inputval){
let inputAction = window.location.pathname;
$.ajax({
type: "POST",
url: inputAction,
data: {order: inputval.split('-')[0].trim(), lot: inputval.split('-')[1].substring(0,5)},
success: function(data) {
$('#product').val('');
//Another function to add HTML
display(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("XHR" + jqXHR)
console.log("Status" + textStatus)
console.log(errorThrown)
}
});
}
Controller File
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (!product || err){
throw new Error("The product entered returns null");
}
res.json(product);
});
};
Main File: app.js
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
});
You should use correct status code for your response. I suggest change your controller like below snippet
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (err){
res.status(500).end();//means internal server error
} else if (!product) {
res.status(404).end();//means product not found
} else {
res.json(product);
}
});
};
I finally figure it out thanks to feedback from other community, so I thought I would just share it here. It's so simple and silly me for neglecting such statement.
First, the code in app.js can just be removed.
Second, based on the answer given by #Milad Aghamohammadi. Instead of just:
res.status(500).end();
Use:
return res.status(500).json({err: "Server error"});
This way, the error is able to be handled by the AJAX error function and the node server will not be terminated from the event loop.
I'm trying to populate data from my DB using Angular and some API services.
My code:
$http.get("/api/trips")
.then(function (response) {
angular.copy(response.data, vm.trips);
}, function (error) {
vm.errorMessage = "Failed to load data: " + error
});
And my API GET() :
[HttpGet("")]
public IActionResult Get()
{
var results = _repository.GetTripsByUsername(this.User.Identity.Name);
return Ok(Mapper.Map<IEnumerable<TripViewModel>>(results));
}
No data is showing. I'm pretty sure the errors is popping because the this.User.Identity.Name is passed wrongly, but I'm confused.
If I change the method from GetTripsByUsername to GetAllTrips , which select all the trips without filter, then the data is shown properly in the page.
The function it self works, if I use it via PostMan, it recognize my cookie and bringing me the correct trips(inside postMan) but on the page it doesn't work ..
It doesn't because your angular application is not authenticated and this.User.Identity.Name is null.
You need to send credential in your angular code like that:
$http.get("/api/trips", { withCredentials: true })
.then(function (response) {
angular.copy(response.data, vm.trips);
}, function (error) {
vm.errorMessage = "Failed to load data: " + error
});
But it depends on your authentication mecanism, This code will not work for Oauth or Basic authentication. If you use Oauth, you must send the Authorization header containing the authorization token.
I am working on this code and I have a really weird issue. I am using AngularJS $http request, and trying to run a success or error afterwards. I am currently getting a 404 from the server (the client says) but the server isn't barfing up a 404 (in fact it says it sent a 200 response).
This $http post doesn't hit either the 'success' or 'error' handlers and I don't know what to do for debugging it.
All other functions using RequestService work perfectly.
var refreshBusinesses = function() {
console.log("refreshBusinesses");
RequestService.post('user/managed_businesses', {}).then(function(businesses){
console.log('got busineses ', businesses)
$scope.businesses = businesses
}, function(error){
console.log("ERROR!");
$scope.error = error.message;
console.log('business refresh error ', error)
})
}
Most probably your service RequestService does not handle promise properly. I believe it is a wrapper around angular's $http. If so, probably it does not reject promise on error, but simply returns some value.
So to solve it check your RequestService that it handles error situation properly:
$http.post('url', data).then(
function(res) {
return res;
},
function(error) {
var deferred = $q.defer();
return deferred.reject(error);
});
$q docs can be found here https://docs.angularjs.org/api/ng/service/$q
I am having issues trying to gracefully handle $http errors. I am looping over a list of servers to make API calls to for status. The calls that complete successfully for perfectly. The ones that fail are not giving me access to the error information. It is always undefined. Here is the code snippet:
angular.forEach($scope.servers, function (server) {
// blank out results first
server.statusResults = {};
$http.jsonp(server.url + '/api/system/status?callback=JSON_CALLBACK', {headers: { 'APP-API-Key': server.apiKey }}).
success(function (data, status, headers, config) {
server.statusResults = data;
}).
error(function (data, status, headers, config) {
// data is always undefined here when there is an error
console.error('Error fetching feed:', data);
});
}
);
The console output shows the correct 401 error (which I didn't output) and my console error message (which I did output) with an undefined data object.
GET https://server_address/api/system/status?callback=angular.callbacks._1 401 (Unauthorized) angular.min.js:104
Error fetching feed: undefined
What I am trying to do is NOT have Angular display the 401 in the log, and instead I will display it in a graceful way. However since data is undefined I have no way of accessing the information.
I am new to AngularJS, but my example closely matches other examples I've found in the documentation.
I've also tried using $resource instead of the $http and got the exact same problem.
var statusResource = $resource(server.url + '/api/system/status', {alt: 'json', callback: 'JSON_CALLBACK'},
{ status: {method: 'JSONP'}, isArray: false, headers: { 'APP-API-Key': server.apiKey } });
// make status API call
statusResource.status({}, function (data) {
server.statusResults = data;
}, function (err) {
// data is always undefined here when there is an error
console.log(err);
});
I'm probably doing something obviously wrong, but I'm not sure what else to try.
Per the $http docs, body is
The response body transformed with the transform functions.
With the 401 (Unauthorized) error you are getting back, it is quite possible there is no body being returned, hence why it is undefined.
If you want to log the error code, log the status parameter instead. It contains the HTTP Status Code, which should be uniform, unlike response bodies.
Im trying to get a working http.get client function working in Meteor.
However I keep getting my own page as result.
Here is my code:
Meteor.http.get("api.openweathermap.org/data/2.5/weather?q=London,uk", function (error, result) {
if(error) {
console.log('http get FAILED!');
} else {
console.log('http get SUCCES');
if (result.statusCode === 200) {
console.log('Status code = 200!');
console.log(result.content);
}
}
});
I would expect that it returned a json object containing weather information.
Do I miss something here?
Thanks.
Please update the url by adding http:// at beginning.
Moreover make this call from your server, i.e. Make a method that contains the above code and call that method via Meteor.call();
Please see Meteor.methods() and Meteor.call()