I'm trying to retrieve the parameters of a GET request as follows but anything I try logs out as 'undefined':
GET
// Find a list of Players
$scope.find = function() {
$scope.players = Players.query({limit: 50});
};
Middleware
//Players service
angular.module('players').factory('Players', ['$resource',
function($resource) {
return $resource('players/:playerId', { playerId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
End Point
exports.list = function(req, res) {
Player.find().sort('-created').limit(req.body.limit).populate('user', 'displayName').exec(function(err, players) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(players);
}
});
};
A good discussion on GET with message body - Is this statement correct? HTTP GET method always has no message body
In short, the behavior of servers when using message body with GET would probably not be consistent.
As my request is a GET I need to attain the parameters (within the query string) using .query:
Player.find().sort('-created').limit(req.query.limit).populate('user', 'displayName').exec(function(err, players) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(players);
}
});
};
This answer was greatly helpful More info
Related
I want to delete all data in my database by a single click.but it gives
"DELETE http://localhost:8080/api/deleteAll 404 (Not Found)".
Can anyone help with this?
Below codes are my attempt.
Controller
$scope.deleteAllData = function () {
Event.deleteAll()
.success(function(){
console.log("All Deleted");
})
.error(function (error) {
$scope.status = 'Unable to load event data: ';
});
};
Service
deleteAll : function() {
return $http.delete('/api/deleteAll');
},
Route
var filesReadUploads = require('./models/readUploadFile');
app.delete('/api/deleteAll', function(req, res) {
filesReadUploads.remove({},function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
});
});
Thanks
I've been given some AngularJS code that has a factory function that is called from a Directive that Posts a file to Web API. I'm having trouble passing the key that is returned to my controller. Can someone tell me how I can do this?
Here is my factory function that posts my file:
return fileManagerClient.save(formData)
.$promise
.then(function(result) {
if (result && result.files) {
result.files.forEach(function(file) {
if (!fileExists(file.name)) {
service.files.push(file);
}
});
}
appInfo.setInfo({
message: "files uploaded successfully"
});
return result.$promise;
},
function(result) {
appInfo.setInfo({
message: "something went wrong: " + result.data.message
});
return $q.reject(result);
})['finally'](
function() {
appInfo.setInfo({
busy: false
});
service.status.uploading = false;
});
}
and I'm trying to get result.value (which is the key of the posted file) passed into my controller but I'm not sure how to do it.
Any help is appreciated.
Thanks,
Pete
If what you say is true, then you just need to have the then callback return result.value:
.then(function(result) {
if (result && result.files) {
result.files.forEach(function(file) {
if (!fileExists(file.name)) {
service.files.push(file);
}
});
}
appInfo.setInfo({
message: "files uploaded successfully"
});
return result.value;
}
In your controller:
myFactory.myFactoryFunction(formData)
.then(function (key) {
console.log(key);
});
When i try to remove one post from view apparently shows that it is removed. However when i go back in providers route i can find all the previous member of array through below route . However when i am in route of /posts doesn't show me previous removed members. Interesting it is that after refreshing page it doesn't show me record on my view anymore.
In following route, post disappear while i try it from command prompt :
/providers/553b72c9f6d0020425d37f37/posts
router.get('/providers/:provider/posts', function(req, res) { Provider.findById(req.params.provider).select('posts').populate('posts').exec(function(err, provider) {
if(err){ return next(err); }
res.json(provider.posts);
});
});
However in this route, i can find posts array with 9 member. It seems that any of the removed doesn't work.
router.get('/providers', function(req, res, next) {
Provider.find(function(err, providers){
if(err){ return next(err); }
res.json(providers);
});
});
Here is my remove function in server side:
router.delete('/providers/:provider/posts/:post',auth, function(req, res){
console.log("I ma running from server")
return Post.findById(req.params.post, function(err, post){
return post.remove(function(err){
if(!err){
Post.update({_id: post.provider}, {$pull : {posts : post._id}}, function(err, numberAffected){
console.log(numberAffected);
if(!err){
return console.log('removed post id');
} else {
return console.log(err);
}
});
console.log('post removed');
return res.send('');
} else{
console.log(err);
}
});
});
});
And here what i have inside my factory in client side:
ob.deletePost = function (provider_id,post_id) {
return $http.delete(urlBase +'/providers/' + provider_id +'/posts/' + post_id ,
{
headers: {Authorization: 'Bearer '+auth.getToken()}
});
};
And in controller:
$scope.deletePost= function (provider_id,post_id) {
//console.log('PROVIDER',provider_id);
// console.log('POST',post_id);
// console.log('COMMENT',comment_id);
providers.deletePost(provider_id,post_id)
.success(function () {
$scope.status = 'Deleted Post! Refreshing post list.';
for (var i = 0; i < $scope.provider.posts.length; i++) {
var post = $scope.provider.posts[i];
// console.log(i,comment,comment_id)
//console.log(comment.ID);
if (post._id === post_id) {
//console.log(provider._id === provider_id)
// console.log(provider._id);
$scope.provider.posts.splice(i, 1);
//providers.getAllComments();
break;
}
}
// $scope.providers = null; // i am not sure how to write for comment as well?
})
.error(function (error) {
$scope.status = 'Unable to delete comment: ' + error.message;
});
};
And here is one part of my view:
<div ng-repeat="provider in providers"> <!-- | orderBy:'-upvotes'-->
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(provider)"></span>
<span style="font-size:18px; margin-left:10px;">
{{provider.upvotes}} - <strong>{{provider.name}}</strong>
<span ng-if="provider.posts.length !== 0">
<a ui-sref="post({provider_id : provider._id})">{{provider.posts.length}} Posts </a>
<button class="btn btn-xs btn-info pull-right" ng-click="modalUpdateProvider('size',provider)">Edit</button>
</span>
Never provider.posts.length is updating. For watching provider and post views you can review following link.
Thank you.
I believe you are using the wrong model in your update statement:
router.delete('/providers/:provider/posts/:post', auth, function(req, res) {
console.log("I ma running from server");
// NOTE: you could also include a where clause to ensure the
// provider ID matches as well. This would prevent someone from using any
// provider ID (inclduing one that doesn't exist) with a post ID.
return Post.findById(req.params.post, function(err, post) {
// Might want to check for an error here
console.log('post removed');
return post.remove(function(err) {
if (!err) {
//Post.update({
Provider.update({
_id: post.provider // or req.params.provider
}, {
$pull: {
posts: post._id
}
}, function(err, numberAffected) {
console.log(numberAffected);
if (!err) {
console.log('removed post id');
} else {
console.log(err);
}
return res.send('');
});
} else {
console.log(err);
}
});
});
});
Also, you could use the findByIdAndXXX methods as well as the built in promises to chain these together for easier readability:
router.delete('/providers/:provider/posts/:post', auth, function(req, res) {
console.log("I ma running from server");
// NOTE: you could also include a where clause to ensure the
// provider ID matches as well. This would prevent someone from using any
// provider ID (inclduing one that doesn't exist) with a post ID.
return Post.findByIdAndRemove(req.params.post).exec().then(function(post) {
console.log('post removed');
return Provider.findByIdAndUpdate(req.params.provider, {
$pull: {
posts: post._id
}
}, {
new: true
} // Return updated document
).exec(); // return promise to be evaluated for next handler
}).then(function(provider) {
console.log('removed post id');
res.send('');
}).then(null, function(err) {
console.log(err);
//might want to send a response error here
});
});
Update: to use a where clause you will need to switch to findOneAndXXX methods:
router.delete('/providers/:provider/posts/:post', auth, function(req, res) {
console.log("I am running from server");
return Post.findOneAndRemove({_id: req.params.post, provider_id: req.params.provider}).exec().then(function(post) {
console.log('post removed');
return Provider.findByIdAndUpdate(req.params.provider, {
$pull: {
posts: post._id // or req.params.post
}
}, {
new: true
} // Return updated document
).exec(); // return promise to be evaluated for next handler
}).then(function(provider) {
console.log('removed post id');
res.send('');
}).then(null, function(err) {
console.log(err);
//might want to send a response error here
});
});
Im trying to publishUpdate some data from the server in order to listen for user/profile creation but im not able to listen to those events in the client using Angular. Is it possible im missing something here? Or maybe something wrong im doing?
// UserController
saveUser: function(req, res) {
User.create({name: req.param('name'), profile: {aboutMe: req.param('about'), gender: req.param('gender')}})
.exec(function(err, user) {
Profile
.findOneById(user.profile)
.exec(function(err, profile) {
profile.user = user.id;
profile.save(function(error, saved){
if (error) return res.badRequest('Error.');
if (saved) res.json(saved);
Profile.publishUpdate(saved.id, saved);
});
});
});
}
// Client Angular
$scope.send = createUser;
listenProfile();
function createUser() {
var obj = {
name: $scope.name,
about: $scope.profile.about,
gender: $scope.profile.gender
User.create(obj).then(function(data) {
console.log(data); // Data displayed correctly
}, function(error) {
console.log(error);
});
}
function listenProfile() {
io.socket.on('profile',function(data){
console.log(data); //Nothing happens?
});
};
Try changing it to a capital P:
function listenProfile() {
io.socket.on('Profile',function(data){
console.log(data); //Nothing happens?
});
};
I think that are missing "suscribe" to your model... for example
Profile.subscribe(req.socket, data);
And linked to your app via GET.
io.socket.get("/profile",function(data){
console.log(data);
});
I am building an angularJS based application and I am running passportjs on my nodeJS back-end.
Authentication works but error handling is not a precise as I want it to be. For example when I am querying my mongoDB and something fails I do the following:
Node:
response.send(406, {error: "Email already in use"});
Angular:
settingsService.saveUserOnServer($scope.settings).then(
function (user) {
//Success
},
function (response) {
console.log(response);
var error = response.data.error;
$cordovaToast.show(error, 'short', 'bottom');
});
This will toast "Email already in use". I want to have the same functionality when using passportjs:
// if no user is found, return the message
if (!user)
return done(null, false, {message: 'No user found'});
This is the response I get in angular:
Object {data: "Unauthorized", status: 401, headers: function, config: Object, statusText: "Unauthorized"}
How can I retrieve the 'No user found' message? Thanks in advance!
Fixed it by using a custom callback:
app.post('/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user, info) {
console.log(info);
if (err) {
return next(err);
}
if (!user) {
res.send(401, info);
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
res.send(user);
});
})(req, res, next);
});
explanation