update and put routes responding error 500 - angularjs

I'm having difficulty setting up put and delete roots in a project the get and post methods at the same url are working fine. Currently, I'm getting an error 500 and a degree of debugging makes me think that the error is in the $http call. For the put route
factory.update(question) is called:
o.update = function(question) {
console.log('update was called')
return $http.put('/questions', question).success(function(data){
o.questions.push(data);
});
};
Which should call the put route in the express routes file:
/*UPDATE question*/
router.put('/questions', function(req, res, next){
console.log('made it to index.js');
var question = req.body;
question.title = req.body.title;
question.type = req.body.type;
question.key = req.body.key;
question.options = req.body.options;
question.save(function(err){
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(article);
}
});
});
For the delete route factory.remove(question) is called:
o.remove = function(question) {
return $http.delete('/questions', question).success(function(data){
o.questions.push(data);
});
}
Which should in turn call the delete route in the express routes file:
/*DELETE question*/
router.delete('/questions', function(req, res, next){
var question = req.body;
article.remove(function(err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(article);
}
});
});
It seems that in both cases the methods in the express routes file are never called which is strange because nearly identical $http requests work elsewhere in the code just fine. How do access my api?

Related

Axios post error

I am trying to post to my api endpint, I get the error:
Uncaught (in promise) Error: Network Error
at createError (C:\sites\LYD\node_modules\axios\lib\core\createError.js:16)
at XMLHttpRequest.handleError (C:\sites\LYD\node_modules\axios\lib\adapters\xhr.js:87)
My axios post is:
submitForm(UserDetails) {
let self = this;
self.show();
axios
.post('http://localhost:3001/api/users', UserDetails)
.then(function(response) {
self.hide();
});
}
My node error is:
C:\sites\LYD>node server
api running on port 3001
(node:11808) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:555:11)
at C:\sites\LYD\server\index.js:75:20
at C:\sites\LYD\node_modules\mongoose\lib\model.js:3809:16
at C:\sites\LYD\node_modules\mongoose\lib\services\model\applyHooks.js:164:17
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Any ideas?
My server.js is:
//first we import our dependencies...
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('../models/users');
//and create our instances
const app = express();
const router = express.Router();
//set our port to either a predetermined port number if you have set it up, or 3001
const port = process.env.API_PORT || 3001;
//db config -- REPLACE USERNAME/PASSWORD/DATABASE WITH YOUR OWN FROM MLAB!
const mongoDB =
'mongodb://dxxx#aws-eu-west-1-portal.4.dblayer.com:10204/xxx?ssl=true';
mongoose.connect(mongoDB, { useMongoClient: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//now we should configure the APi to use bodyParser and look for JSON data in the body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,HEAD,OPTIONS,POST,PUT,DELETE'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!' });
});
//adding the /comments route to our /api router
router
.route('/users')
//retrieve all comments from the database
.get(function(req, res) {
//looks at our Comment Schema
User.find(function(err, users) {
if (err) res.send(err);
//responds with a json object of our database comments.
res.json(users);
});
})
//post new comment to the database
.post(function(req, res) {
var NewUser = new User();
req.body.accessCode ? (NewUser.accessCode = req.body.accessCode) : null;
req.body.age ? (NewUser.age = req.body.age) : null;
req.body.drinkConcern
? (NewUser.drinkConcern = req.body.drinkConcern)
: null;
req.body.drinkOften ? (NewUser.drinkOften = req.body.drinkOften) : null;
req.body.ethnicity ? (NewUser.ethnicity = req.body.ethnicity) : null;
req.body.gender ? (NewUser.age = req.body.gender) : null;
req.body.language ? (NewUser.language = req.body.language) : null;
NewUser.save(function(err) {
if (err) res.end(err);
res.json({ message: 'Comment successfully added!' });
});
});
//Adding a route to a specific comment based on the database ID
router
.route('/users/:id')
//The put method gives us the chance to update our comment based on the ID passed to the route
.put(function(req, res) {
Comment.findById(req.params.id, function(err, user) {
if (err) res.send(err);
//setting the new author and text to whatever was changed. If nothing was changed
// we will not alter the field.
req.body.author ? (comment.author = req.body.author) : null;
req.body.text ? (comment.text = req.body.text) : null;
//save comment
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'Comment has been updated' });
});
});
})
//delete method for removing a comment from our database
.delete(function(req, res) {
//selects the comment by its ID, then removes it.
User.remove({ _id: req.params.comment_id }, function(err, user) {
if (err) res.send(err);
res.json({ message: 'Comment has been deleted' });
});
});
//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
I have changed my axios post to this:
let self = this;
self.show();
const headers = {
'Content-Type': 'application/json',
};
axios
.post('http://localhost:3001/api/users', UserDetails, headers)
.then(function(response) {
self.hide();
});
You can change the mongoose query to,
let query = {} //or any other query
User.find(query,function(err,res){
...
})
I think the problem is with your routes.
When you create a route instead of using router.route('/route').post(function(req, res) { ... }, use router.post('/route', function(req, res) { .... } (obviously change .post to the method you want to use)
In your code this would be:
router
.get('/users', function(req, res) {
User.find(function(err, users) {
if (err) res.send(err);
res.json(users);
});
})
I think you can only do app.route('/route').get(...).post(...) but not with router
Look at the express routing documentation for more info: https://expressjs.com/en/guide/routing.html

put operation in Node.js

For put request:
router.put('/:id', controller.update);
My update method look like this:
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Thing.findById(req.params.id, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) { return res.status(404).send('Not Found'); }
var updated = _.merge(thing, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(thing);
});
});
};
Making request:
$http.put('/api/things/'+ thing._id, updatedThingObject)
.success(function(update){
console.log("update", update)
})
.error(function(err){
console.log("err", err)
})
It gives connection error on passing the object while making the request in angular.
The error looks like this:
PUT http://localhost:9000/api/things/56c8325b9a0ee7d00d266495
net::ERR_CONNECTION_REFUSED(anonymous function) # angular.js:11442sendReq #
If I take off the updated object, it makes the request just fine but ofcourse nothing gets updated in
that case. What might be wrong here,please?
I figured.
The reason for the functions not being called is that I have a function that is being called repetitively in Node .
var autoCreate = function(){
console.log("THING CREATED AUTOMATICALLY")
var randomNumb=0;
clearTimeout(randomNumb);
randomNumb = (Math.random()* (10-5) + 5).toFixed(0);
console.log("random number", randomNumb)
var randomThing =randomstring({
length: randomNumb,
numeric: false,
letters: true,
special: false
});
console.log("ranfom thing", randomThing)
Thing.create({
name: randomThing,
readByUser: false
}, function(err, thing) {
console.log("THING IS", thing)
//setTimeout(autoCreate, randomNumb * 1000);
});
}
setTimeout(autoCreate, 10*1000);
Since this is running when post/put request is made, I get connection error. How do I handle this to be able to have this function running and be able to make put/post requests as well?

NodeJS - Cannot set headers after they are sent - Multiple Calls

I'm trying to write an app that find a city in a MongoDB collection and uses the latitude and longitude it returns to find all zip codes within a certain distance. It seems to work, but the problem is that I'm getting an error that I can't set headers after they've already been sent. However, I've separated the to routes into different requests I don't understand why I'm still getting this error. What is the best way to make multiple calls to the API?
Here is my router in Node/Express:
// route to get city
app.get('/cities/:zip', function(req, res) {
// use mongoose to get the city in the database
console.log(req.params.zip);
var query = City.find({"zip" : req.params.zip});
query.exec(function(err, city) {
if (err)
res.send(err);
res.json(city);
});
});
// route to find cities within 50 miles
app.get('/matches/:latMin/:latMax/:lonMin/:lonMax', function(req, res) {
console.log(req.params.latMin + req.params.latMax + req.params.lonMin + req.params.lonMax);
var matches = City.find({latitude: {$gt: req.param.latMin, $lt:req.params.latMax }, longitude : {$gt :req.param.lonMin, $lt : req.param.lonMax}});
matches.exec(function(err, match){
if(err)
res.send(err);
console.log(match);
res.json(match);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
});
Here is my Angular Controller
$scope.update = function (zip) {
City.get({zip : zip}).success(function(response){
$scope.weather = response
}).then(function(response){
$scope.weather = response.data;
})
if(zip.length = 5){
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK&units=imperial').success(function(data){
$scope.data=data;
});
var box = getBoundingBox([$scope.weather[0].latitude, $scope.weather[0].longitude], 50);
City.matches(box[1], box[3], box[0], box[2]).success(function(response){
$scope.matches = response
}).then(function(response){
$scope.matches = response.data;
console.log($scope.matches);
})
}
res.send does not return; the call continues to res.json. And please use braces. Please. Maybe they don't look cool or whatever. Just use them.
if (err) { handleError(res, err); return; }
res.status(200).json(city);
Further down, keeping things DRY:
function handleError(res, err) {
res.status(500).json(err);
}

Updating database with node.js and angular

I have an app which posts, gets and deletes data and I would like to add 'update' functionality as well but I can't figure it out..
I have a node.js server which has such api:
app.get('/api/feedbacks', function(req, res) {
// use mongoose to get all feedbacks in the database
getfeedbacks(res);
});
// create feedback and send back all feedback after creation
app.post('/api/feedbacks', function(req, res) {
// create a feedback, information comes from AJAX request from Angular
FeedBack.create(req.body, function(err, feedback) {
if (err)
res.send(err);
// get and return all the feedbacks after you create another
getfeedbacks(res);
});
});
// delete a feedback
app.delete('/api/feedbacks/:feedback_id', function(req, res) {
FeedBack.remove({
_id : req.params.feedback_id
}, function(err, feedback) {
if (err)
res.send(err);
getfeedbacks(res);
});
});
and such angular service which speaks to node api:
service.factory('FeedBacks', ['$http',function($http) {
return {
create : function(feedBackData) {
return $http.post('/api/feedbacks', feedBackData);
},
get : function() {
return $http.get('/api/feedbacks');
},
delete : function(id) {
return $http.delete('/api/feedbacks/' + id);
}
}
}]);
That way I can post, get and delete data.
My goal is to add also update function.
What I have tried on node:
// update a feedback
app.put('/api/feedbacks/:feedback_id', function(req, res) {
// edit a feedback, information comes from AJAX request from Angular
FeedBack.put(req.body, function(err, feedback) {
if (err)
res.send(err);
// get and return all the feedbacks after you edit one
getfeedbacks(res);
});
});
on Angular service:
update: function(editFeedId, editedFeed){
return $http.put('/api/feedbacks/' + editFeedId, editedFeed);
}
controller looks like:
$scope.editFeed = function(id) {
$scope.editFeedId = id;
$scope.editedFeed = 'replace this txt'
FeedBacks.update($scope.editFeedId, $scope.editedFeed)
// if successful creation, call our get function to get all the new
feedBacks
.success(function(data) {
console.log('updated');
$scope.feedbacks = data;
});
};
I get 500 error as I execute editFeed(). I couldn't figure out to configure that! Where do I do wrong? Any Tips?
Thanks a lot in advance!
I'm assuming you're using Mongo here, in which case your update statement is incorrect.
It should be something like:
app.put('/api/feedbacks/:feedback_id', function(req, res) {
FeedBack.update({_id: req.params.feedback_id}, req.body, function(err, feedback) {
if (err)
res.send(err);
// get and return all the feedbacks after you edit one
getfeedbacks(res);
});
});

Passport.js Google authentication returns blank error

Trying to use passport.js in my Angular app to use google authentication.
The way I have my express endpoints set up is:
app.set('client-google-signin-path', '/google');
app.route('/auth/google')
.get(function(req, res, next) {
var mobileApp = req.headers.origin;
passport.authenticate('google', { scope: ['profile', 'email'], callbackURL: mobileApp + req.app.get('client-google-signin-path')})(req, res, next);
});
app.route('/auth/google/callback')
.get(function(req, res, next) {
//NEVER MAKES IT HERE
var mobileApp = req.headers.origin;
passport.authenticate('google', {scope: ['profile', 'email'], callbackURL: mobileApp + req.app.get('client-google-signin-path')},
function(err, user, info) {
var profile;
if(err) return next(err);
if(!info || !info.profile) return res.status(400).send("Profile not available.");
// Grab the profile info returned from google.
profile = info.profile._json;
//model logic
User.findOne({ 'email': profile.email }, function(err, user) {
if(err) return next(err);
if(!user) return res.status(400).send("There does not appear to be an account that matches, you may need to create an account and try again.");
req.logIn(user, function(err) {
if(err) return next(err);
return res.status(200).send(user);
});
});
res.status(200);
})(req, res, next);
});
My controller looks like:
$scope.signInGoogle = function() {
return $http.get(backendConst.location + 'auth/google')
.success(function(url) {
// Redirect to google.
$window.location.href = url;
});
};
$scope.signInGoogleCallback = function() {
return $http.get(backendConst.location + 'auth/google/callback', {
params: $location.search()
})
.success(function(user) {
$scope.gRes = 'Success!';
$location.search('code', null);
$location.hash(null);
AuthModel.setUser(user);
$location.path('/');
})
.error(function(err) {
$scope.gRes = 'Authentication failed, redirecting.';
$location.path('/authenticate');
});
And for good measure, my dinky little /google redirect page is:
<div class="container clearfix" ng-init="signInGoogleCallback()">
<h1>Google YO!</h1>
<h4>{{gRes}}</h4>
</div>
So what's happening is that it brings in the "log in with google" page, lets me select my account, then when it calls the callback it quickly flashes the /google view but then kicks me back out into /authenticate, the view I started in. Doing some debugging shows that
return $http.get(backendConst.location + 'auth/google/callback', {
params: $location.search()
})
is throwing a blank "err" even though in my endpoint logs it's saying that /auth/google/callback returned a 200. I'm not sure what's happening. I know this looks needlessly complicated but I do it this way with facebook and passport.js and everything works fine, except my endpoint logs are showing that with facebook the parameter "?code=" is being added to the /auth/facebook/callback url, like I'm trying to do with {params: $location.search()} in my google callback function in my controller. Debugging into the endpoint shows that it never makes it to where I left the //NEVER MAKES IT HERE comment, but when removing the {params: $location.search()} option it makes it passport.authenticate but not beyond. I'm completely stumped. Again I should stress that I handle facebook authentication the exact same way and it works perfectly.

Resources