PUT request not working in Node.js - angularjs

I am trying to update an existing document in mongodb with node.js. But it does not seem to work. It do not even display the request call in the console. Please suggest what mistake I am doing or how I can I do the update operation in node.js with mongodb. Here is the code:
Node.js Code:
app.put('/addIssueId', function(req, res) {
console.log("Adding issue id")
console.log(req.body.issueKey)
impactMapFeature.update( {productName:req.params.productName, actor:req.body.actor, activity:req.body.activity,feature:req.body.feature},{issueKey:req.body.issueKey}, function ( err, data ) {
console.log("Updating" + data)
});
});
Angular Controller code:
var data = {
productName: $scope.productName,
actor: actor,
activity: impact,
feature : $('#feature').val(),
issueKey : data.key
};
$http.put('/addIssueId', data)
.success(function(data){
}).error(function(data){
console.log('Error in adding issueId' + data)
});
}

As chridam said, you are using req.params which is a route parameter. Either use the following route : /addIssueId/:productName or pass your variable with a query parameter : /addIssueId?productName=productName and {productName = req.query.productName, ... }, or pass your variable as you are doing it in the body (then you just need to change req.params.productName to req.body.productName

Related

POST request using angular $resource

In my index.js file I have the following POST...
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
I test the url http://localhost:8080/api/bears with a POST request on Postman and it was successful. Now I'd like to test my POST request using angular $resource.
I tried the following which I got from the documentation...
app.factory('Profile', function ($resource) {
var Bear = $resource('http://XXX.XXX.X.XX:3000/api/bears/:bearId', {bearId:'#id'});
var single_bear = Bear.post({bearId:123}, function(){
single_bear.name = "Yogi";
single_bear.$save();
});
});
I'm not sure what I should for bearId, I just put a random number. And I am trying to save the bear's name as Yogi. I'm assuming this POST request will occur when I run the app, but I do so and then check to see if my db was filled and there is no entry.
What am I doing wrong?
EDIT
in case you're wondering what a bear entry looks like...
{
"_id": "57ded2302a5ebc050ce3852d",
"__v": 0,
"name": ""
}
Your resource is configured to look for the id property in the data passed (via '#id') yet your data is passing bearId.
Additionally, the data from your server seems to have an _id property, not id nor bearId.
Also, the resource method you're looking for is save(), not post().
I'd go with this type of resource definition...
$resource('http://XXX.XXX.X.XX:3000/api/bears/:id', {id:'#_id'});
Then, you can use it to create a new Bear via
Bear.save({_id: 123, name: 'Yogi'})

unable to retrieve request param in node js

In my angular js factory, i am making an ajax call to transfer the input model value to the server side ( node js) but when i try to retrieve it , i see 'undefined' .
angular js :
angular.module('name-App').factory('myService', function($http,$rootScope) {
return {
getFoos: function(stock) {
console.log("----------->"+stock.toString());//displays the value correctly over here .
//return the promise directly.
return $http({
url:'http://localhost:3000/gethistorydata',
method: "GET",
params: stock
}).then(function(result) {
alert("result.data"+result.data);
return result.data;
}).catch(function(fallback) {
alert("failed"+fallback + '!!');
});
}
}
});
In node js i have below :
app.get('/gethistorydata',function(req,res){
console.log("--------------->>>>>>");
console.log("stock name = "+req.params.data);
//res.cookie();
//res.sendFile("F:/customer/public/index.html");
});
req.params.data is undefined . whats wrong with syntax?
req.params refers to url path parameters. So you would have to add one to your route for it to be supported. For example a request to /gethistorydata/123 with this route defined(note the added /:id on the end):
app.get('/gethistorydata/:id, function(req, res) {
console.log('my id is ' + req.params.id');
});
would log "my id is 123".
I think you are looking for req.query. What does your stock object look like? If it looked like this {"price": 123} angular would modify the request to look like /gethistorydata?price=123 and you could change your code to this:
app.get('/gethistorydata, function(req, res) {
console.log('my stock price is ' + req.query.price');
});
which would log "my stock price is 123"
See the docs for more examples http://expressjs.com/en/api.html#req.query

show current user information from node to angular

I want to show current user information from nodejs to angular(view).
The problem is that i don't know how to pass and how to get User Id in node and angular .
Code :
Node
router.get('/:id/api/data.json', function(req, res, next) {
console.log(req.params.id);
var userId = req.params.id;
User.findById({_id:userId}, function (err, doc) {
if (err) throw err
if (doc){
res.json({
doc: doc,
userID:req.params.id
});
}
});
});
Angular :
app.controller('profileCtrl', function($scope, $http) {
$http.get("don't know how to get id from node").then(function (response) {
console.log(response.data);
});
});
Your Node.js router is listening to the url /:id/api/data.json. The :id part of that means Node.js is expecting a paramater there, which will get picked up by req.params.id in your Node.js file.
This means that you actually have to be passing in an id value as a part of the url. So your url would look something like /userid12345/api/data.json.
In your Angular file, that's the url you're going to be making the get request to. Which means you need to know the user's ID in your Angular file so you can get that specific url, e.g.:
var userId = 'userid12345';
$http.get('/' + userId + '/api/data.json').then(function(response) {
console.log(response);
});
Once you pass userId in as a part of the url, then Node can grab it using req.params.id and you can make your db call.

PUT and POST Angularjs

I have an Ionic project with a WCF RESTful service, I want to be able to Insert and Update data. I can already view data with GET method but can't find anything on the internet for PUT and POST. How would I be able to accomplish this?
GET Method
$scope.selectedDist= function() {
$http.get("http://192.168.1.113/Service1.svc/GetAllComp")
.success(function(data) {
var obj = data;
var ar = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
ar.push({CompID: indexN.CompID, CompName: indexN.CompName});
$scope.districts = ar;
});
});
})
.error(function(data) {
console.log("failure");})
};
Post methods I tried
#1
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http.post("http://192.168.1.113/Service1.svc/GetAllComp", ar)
.success(function(data)
{
console.log("data inserted successfully")
})
.error(function(data)
{
console.log("Error")
})
#2
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http ({
url : "localhost:15021/Service1.svc/TruckDetails" ,
Method : "POST" ,
headers : {
'Content-Type' : 'Application / json; charset = utf-8'
},
Data : ar
})
Also Would I need to make a POST or PUT method on my Service as well or can I use the GET methods?
You can use a get method, in combination with a querystring to post and put data but that is not what it was designed for and should be avoided for several reasons such as security.
That being said, it is not that difficult to use post and put in angular and in the following , rather naive service , you can see all that is required to do is passing your data in the service function you're invoking.
.service('MyService', function($http) {
this.postMethod = function(data) {
return $http.post('http://my.url', data);
};
this.putMethod = function(id, data) {
return $http.put('http://my.url/' + id, data);
};
}
So that in your controller you can inject and invoke the service methods with the $scope data that needs to be stored.
After taking a look at your attempts you seem to be using the same url for both get and post: "http://192.168.1.113/Service1.svc/GetAllComp" which actually leads me to believe you haven't thought about implementing these methods on your server. Can you confirm this?
Apart from that, it is always usefull to look at statuscodes when trying to send requests because they provide a great deal of information about the nature of the error that occurs. You can investigate that in either your console or an external program such as Fiddler.
P.S.
Deprecation Notice The $http legacy promise methods success and error
have been deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.

AngularJS reload data after PUT request

Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};

Resources