How to send a message from node.js function to angular controller - angularjs

I have a variable called message in node.js function now I want to send it to angular controller. How to do this?
api.js
router.post('/pages/auth/forgot-password', function(req,res,next){
var maillist = req.body.email;
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email : maillist}, function(err, user) {
if (!user){
return done(null, false,{message: 'No account with that email address exists.'});
return res.redirect('/pages/auth/forgot-password');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000;
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var mailOptions={
to : maillist,
subject : 'Password Recovery',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://192.127.0.1:3000/pages/auth/reset-password/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transport.sendMail(mailOptions, function(error, response){
if(error){
return done(null, false,{message: 'An e-mail has been sent to ' + maillist + ' with further instructions.'});
}
transport.close();
});
}
], function(err){
if (err) return next(err);
res.redirect('/pages/auth/forgot-password');
});
return res.json({result:message});
});
I am trying to send like return res.json({result:message}); But it shows an error called message undefined.

Try to do in your last callback
transport.sendMail(mailOptions, function(error, response) {
if (!error) {
var message = {
message: 'An e-mail has been sent to ' + maillist + ' with further instructions.'
};
done(null, message);
}
transport.close();
});
And in final callback
], function(err,result) {
if (err) return next(err);
return res.json({
result: result.message
});
});

Message is not defined in your code
res.json({ result: 'An e-mail has been sent to ' + maillist + ' with further instructions'})

Message is an undefined variable... Either define it or pass a string or better yet use template literals ---> es6!
At the moment u r firing a bunch of async functions but not waiting for any of them to return before you reply to the frontend.
Using Async waterfall in node.js
I assume once yuo finish the work of the async funciton you want to pass a message back?
If not and u just wana send a message...
return res.json({result:'I am a message string....'});
Based on the comment above...
return res.json({result:`An e-mail has been sent to ${maillist} with further instructions`});

Related

How do I pass route parameter to another route so I can fetch it

What I'm trying to accomplish is having an input box called "Order Number" the user can put in an order number and hit submit. When they hit submit, it redirects to another page where fields would get captured based on that order number that was enterered on the previous page for the input box.
What I have figured out so far is:
passing a post request to the / route which is the page where the input box is on for the user to put in the order number.
With help, I managed to pass the orderNum in the url on the next page
What I'm stuck on is trying to figure out how to fetch the orderNum that I passed in the URL to the new route on the server. Once I can fetch it I'll know how to set it to state and populate the boxes with the orderNum
Hope that was clear enough
My Attempt:
app.post('/', function(req, res){
request.query("select [TableId] FROM [SACH_QA].[Orders].[Order] where [TableId] ='" + req.body.orderNum + "'", function(error, result){
if(error){
throw error;
} else {
//console.log(result);
res.redirect('/relotoForm');
}
});
});
app.post('/reloToForm', function(err, res){
if(err){
throw err;
} else {
// How can I have access to req.body.orderNum from / on this request?
}
});
View:
onSubmit(e){
if(this.state.orderNum === '') {
this.setState({
errorMsg: 'Please enter an order number.'
});
e.preventDefault();
} else {
this.setState({
errorMsg: ''
});
console.log('passed');
// Submit the form
const reloData = {
orderNum: this.state.orderNum
}
fetch('/', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(reloData)
}).catch(function(err){
console.log(err);
})
}
//e.preventDefault();
}
I think you can make a route like this:
app.post('/', function(req, res){
request.query("select [TableId] FROM [SACH_QA].[Orders].[Order] where [TableId] ='" + req.body.orderNum + "'", function(error, result){
if(error){
throw error;
} else {
//console.log(result);
res.redirect('/relotoForm' + '?orderNum=' +req.body.orderNum);
}
});
});
and here you can access it as a orderNum:
app.post('/reloToForm', function(err, res, req){
if(err){
throw err;
} else {
console.log(req.query.orderNum)
}
});
I hope it will work, didnt tryed by myself

PassportJS with NodeJS not returning errors (MEAN stack)

I'm running a MEAN stack with PassportJS for authentication, and I'm having an issue with my signup module interacting with my Angular controller. Basically, the errorCallback is never called, and I'm not sure how to properly use the Passport done() implementation.
I have a basic signup form that upon submission, calls this request:
$http.post('/api/signup', {
name: $scope.user.name,
email: $scope.user.email,
password: $scope.user.password,
userSince: new Date().now
}).then(
function successCallback(res) {
$rootScope.message = 'Account Created';
console.log('Success'+res);
console.dir(res,{depth:5});
$location.url('/signupConf');
}, function errorCallback(res) {
$rootScope.message = 'Failure, see console';
console.log('Error: '+res);
console.dir(res,{depth:5});
$location.url('/');
});
With the express route:
app.post('/api/signup', passport.authenticate('local-signup'),function(req, res) {
console.log('User: ' + req.user.email);
});
And finally the Passport (adapted from a Scotch.io tut) module, abridged a little:
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
console.log("Signup Request: "+email);
process.nextTick(function() {
User.findOne({ 'email' : email }, function(err, user) {
if (err) { return done(err); }
// check to see if theres already a user with that email
if (user) {
console.log("User not created, already exsists: "+user);
return done(err, false, {message: 'Username already exsists.'});
} else {
// if there is no user with that email
// create the user
var newUser = new User();
//a bunch of data creation here
newUser.save(function(err) {
if (err) {throw err;}
console.log("Sucessfully created: "+newUser);
return done(null, newUser);
});
}
});
});
}));
Everything runs fine, users are created corrected, and if a user with a given email exists, a new one isn't written over it. However, no matter what, successCallback is called. When a username already exist, I can see a 401 error in the browser console. When its a bad request (i.e. not all fields filled), a 400 error.
All the server side console.logs work fine, leading me to think there's something wrong in my angular frontend, or how the backend is responding to the request.
(Scotch.io tutorial credit: https://scotch.io/tutorials/easy-node-authentication-setup-and-local)
The problem was sort of staring me in the face, it was in my route handling.
app.post('/api/signup', function(req, res, next) {
passport.authenticate('local-signup', function(err,user,response) {
//handle responses based on state of user and err
})
(req, res, next);
});

How do I process responses from express with angular?

This is for a project for college. I am having difficulty understanding how to handle express responses with angular. My partner handled most of the back end and I took care of most of the front end, as to how to get information from express and use it on the front end. Our routing is below, if it will help.
// set variables for environment
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
//tell express to use the bodyParser middleware
app.use(bodyParser());
//start the mysql interface
var mysql = require('mysql');
var mysql = require('mysql');
var connectionPool = mysql.createPool({
host : 'localhost',
user : '<user>',
password : '<password>',
database : '<table>'
});
// connection.connect();
// connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
// });
// connection.end();
// Set server port
app.listen(80);
console.log('server is running at 127.0.0.1:80');
// views as directory for all template files
app.set('views', path.join(__dirname, 'views'));
// instruct express to server up static assets
app.use(express.static('public'));
// set routes
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/:file', function(req, res) {
res.sendFile(__dirname + '/views/' + req.params.file);
});
app.get('/req/:itemname', function(req,res)
{
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
else
{
var query = 'SELECT * FROM Product WHERE name LIKE \'%' + req.params.itemname +'%\' ORDER BY ProductID asc';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
res.send({
result: 'success',
err: '',
fields: fields,
json: rows,
length: rows.length
});
}
});
connection.release();
}
});
// connection.destroy();
});
app.post('/login/', function(req,res)
{
//debug for routes to make sure everything is working properly
console.log('I am in the login post route');
//connect to SQL pool
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error, having issue connecting to MYSQL DB instance',
err: err.code
});
}
else
{
var user = req.body.email;
user = user.toUpperCase();
var password = req.body.password;
console.log('user: ' + user);
console.log('password: ' + password);
var query = 'select COUNT(*) AS recordCount, isStaff from userTable where email = \''+user+'\' AND password = \''+password+'\'';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
//another connection issue
console.log('in 500 error box')
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
//if the query was successful, we check to see if their exists a record of this query
//debug print count of records that match parameters
// console.log(rows[0].recordCount)
//if the return query has a user that has admin privileges, redirect them to the admin page
console.log(rows[0].isStaff);
if(rows[0].recordCount >=1 && rows[0].isStaff == 1)
{
console.log('at least one staff record')
res.sendFile(__dirname + '/views/admin.html')
// next();
}
else if(rows[0].recordCount >=1 && rows[0].isStaff == 0)
{
console.log('at least one nonstaff record')
res.sendFile(__dirname + '/views/customer.html')
// next();
}
else
{
console.log('invalid login')
console.log('in 503 error box, invalid user')
res.statusCode = 503;
res.send({
statuscode: '503',
result: 'E-mail or Password is incorrect',
});
}
}
});
connection.release();
}
});
});
Near the bottom of the code we specifically would like to handle the case when we have a login error. Right now it just sends back {{ statuscode: 503, result: 'E-mail or Password is incorrect'}} on a blank page.
On the front end a modal is displayed requesting sign in information. On success it redirects to a different page. On failure we would like to tell the front end to leave the modal on the page open and post an alert message in the body of the modal.
Please help.
Edit: The purpose of the project is working with the database. The project requires a web based app as the interface and since our next course requires using the MEAN stack we decided to go ahead and start learning a bit on our own.
In your $http call on the frontend, simply pass in a second argument as you error handling callback. The $http service will run that function any time the server sends back an error status.
https://docs.angularjs.org/api/ng/service/$http
$http.get('api/route')
.then(function successCallback(response) {
loginSuccessRedirect();
}, function errorCallback(response) {
handleLoginError();
});

Backbone.js save always triggers error even on success

I've read several of the other posts about this problem and none of the solutions seem to be working for me. I have the following code in my View:
this.model.set({
username: $('#user-username').val(),
role: $('#user-role').val(),
description: $('#user-description').val()
});
this.model.save({ user_id: this.model.get('user_id')}, {
success: function(user, response) {
console.log('success:', response);
$('.flash-message').text("Success").show();
},
error: function(user, response) {
console.log('error:', response);
$('.flash-message').text(response.error).show();
}
});
and this on my server controller (nodejs running express 3):
UserController.prototype.updateAction = function(req, res) {
if (req.route.method != "put") {
res.send({status: "error", error: "update must be put action and must include values"});
return false;
}
var query = {'user_id': req.params.id};
var user = req.body;
var userRepository = this.userRepository
// delete _id to avoid errors
delete user._id;
userRepository.update(query, user, {}, function(err, updated) {
if ((err) || (!updated)) {
res.send({"status": "error", "error": err});
return false;
}
// send updated user back
util.log('updated user ' + user.user_id);
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(JSON.stringify({"status": "success", "updated": updated}));
});
}
On save, my model is saved correctly in the server and I have verified the server response with this. So, as far as I can tell the server is returning status 200, valid JSON, with a valid JSON response header. And yet my backbone model.save function always triggers the error callback. Can anyone please tell me why and how to resolve this?
I am able to get this to work if set the dataType to text like so:
this.model.save({ user_id: this.model.get('user_id')}, {
dataType: "text",
success: function(user, response) {
console.log('success:', response);
$('.flash-message').text("Success").show();
},
error: function(user, response) {
console.log('error:', response);
$('.flash-message').text(response.error).show();
}
});
but doing so does not allow me to get the response back from the server. Instead I get this in the response var:
success: {
"_id": "5133b02062e15ed1d2000001",
}
Backbone expects to get back the model that it sent in its PUT or POST request body.
Instead of:
res.send(JSON.stringify({"status": "success", "updated": updated}));
Try this in your server's response:
res.json(user);
There may be a possibility that your call may have got in state 200 connection established which backbone detects as error, Backbone throws success only when the call is 200OK.
What's your server code? You need to make sure you're sending json back to backbone like so:
//In your express POST route
user.save(function(err) {
if(err){
console.log(err);
return res.json(401);
} else {
console.log('user: ' +user.username + ' saved');
return res.json(200);
}
Then in your backbone view you can check for the response and do what you need:
//some function in your view
this.model.save(this.formValues, {
success: function(model, response, options) {
if (response == 200) {
console.log('success :' + response);
//Do stuff
} else {
console.log('error: '+response);
//etc.
Also note that as per the backbone model documentation:
"save accepts success and error callbacks in the options hash, which will be passed the arguments (model, response, options)"

Backbone.js model.save() - proper server response

Something seems to be wrong, either my server response or my save function.
In neither case success nor error function of model.save() gets invoked.
My server response:
exports.updateBusinessBannerAd = function(req, res) {
// update banner ad
db.insert(req.body, req.body._id, function(err, data) {
if (err) {
console.log('Update business banner ad: ' + err.message + ' ' + err['status-code']);
res.send(err['status-code'], { header: 'Update banner ad', message: err.message, type: 'error'});
}
else {
res.send(200);
}
});
};
And here my client code:
saveBannerAd: function(self) {
self.model.id = self.model.attributes._id;
self.model.save({
success: function(model, res) {
utils.growl( 'Banner Ad', 'has been updated!', 'info');
self.resetHandler();
},
error: function(model, res) {
console.log(res);
utils.growl(res.header, res.message, res.type);
return;
}
});
},
What am I missing?
Okay, adding { id: self.model.get('id') } as first argument to model.save() fixed my issue.
In this thread
someone suggested setting 'null' as first argument serves as placeholder, but my experience is that this will invoke the error function.

Resources