how can i make a post request from a router, it works on the "/" pages but not working on the "/forget" page. when i replace "/forget" page to "/" pages it works fine but when the post method is from "/forget" it give error. here is my code
please help look at it
thanks in advance
this is my "/" pages it works fine here
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
var register = {
Email: req.body.emial,
Password: req.body.password,
C_password: req.body.c_password
}
var newUser = {
Referer_mail : req.body.ref_email,
Name : req.body.name,
Country : req.body.country,
Phone: req.body.phone,
Email: req.body.emial,
Wallet : 0 ,
Invest : 0 ,
Interest : 0 ,
Income : 0,
referal : 0
}
if (register.Password === register.C_password){
firebase.registerWithEmail(register.Email, register.Password, newUser, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
// send emial verification
firebase.sendVerificationEmail(result.token, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
console.log(result);
}
});
// save name in data base
firebase.database().ref("Profile").child(result.user.id).set({newUser}, function (err, result){
if (err){
console.log(err);
Message = err.message;
} else {
console.log(result);
}
})
console.log(result);
}
});
res.render('pages/activate', {
value : Message
});
} else {
console.log("password and confrim password not equal");
res.render('pages/index', {
value : " Your Password and Confrim Password are not equal"
});
}
});
while this is my "/forget" pages give error
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
res.render('pages/activate', {
value : Message
});
});
please help me find time and look at it,
thanks in advance
Related
I've been following a guide on implementing a password reset in Node. I'm working on the password reset post route below and when I post nothing seems to happen, it justs reloads the reset page. ive added some console.log() in various places on the code but they dont get executed. Hope someone can assist. ive deleted the other routes to make the code shorter
var express = require('express');
var router = express.Router({ mergeParams: true });
var Kids = require('../models/kid');
var User = require('../models/user');
var async = require('async');
var nodemailer = require('nodemailer');
var crypto = require('crypto');
var middleware = require('../middleware');
//password reset
router.get('/password_reset', function (req, res) {
res.render('password_reset');
});
//posting the account email reset
router.post('/password_reset', function (req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that email address exists.');
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: {
user: 'Hidden',
pass: 'Hidden'
}
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Node.js Password Reset',
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://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
}
], function(err) {
if (err) return next(err);
res.redirect('/forgot_reset');
});
});
module.exports = router;
i figured out the issue, it was to do with my form. I had forgotten to add:
<form method="post" action="/password_reset">
so the form was not sending anything.
I have two files : server.js and user.js , I want to secure some routes in user.js with a middle-ware written in server.je.
server.js
// :::::: G E T T H E P A C K A G E W E N E E D : : : : : : : :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var cors=require('cors');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
// ─── GET an instance of the router for api routes ────────────────────────────────────────────────────────────────────────
var apiRoutes = express.Router();
var users =require('./app/routes/users');
//
// ────────────────────────────────────────────── II ──────────────────────────────────────────────────────────────────────
// :::::: CONFIGURATION : : : : : : : :
var port = process.env.PORT || 1991; // used to create, sign, and verify tokens
mongoose.connect(config.database, { useMongoClient: true }); // connect to database
app.set('superSecret', config.secret); // secret variable
//
// ────────────────────────────────────────────── III ──────────────────────────────────────────────────────────────────────
// :::::: USE BODY PARSER SO WE CAN GET INFO FROM POST AND/OR URL PARAMETERS : : : : : : : :
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// :::::: USE MORGAN TO LOG REQUESTS TO THE CONSOLE: : : :
app.use(morgan('dev'));
app.use(cors());
// ──────────────────────────────────────────────────────────────
// :::::: R O U T E S : : : : : : : :
// ──────────────────────────────────────────────────────────────
// ─── A P I ROUTES ────────────────────────────────────────
// :::::: MIDDLEWARE to secure route begin with /api: : : :
apiRoutes.use(function(req, res, next) {
console.log('hah');
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
console.log([err,decoded]);
if (err) { //failed verification.
return res.json({"error": true, success:false, message:'Faild to authenticate token'});
}
req.decoded = decoded;
next(); //no error, proceed
});
} else {
// forbidden without token
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to the coolest API on earth!' });
});
app.use('/api', apiRoutes);
app.use('/user', users);
// ──────────────────────────────────────────────────
// :::::: S T A R T the server: : : : : :
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
user.js
const express=require('express');
const router=express.Router();
const passport= require('passport');
const jwt=require('jsonwebtoken');
var userRoutes = express.Router();
var config = require('../../config'); // get our config file
var User = require('../../app/models/User'); // get our mongoose model
//
// ─── ROUTE TO REGISTER USER ──────────────────────────────────────────────────────────────────────
//
userRoutes.post('/signup', function(req, res) {
if (!req.body.email || !req.body.password || !req.body.firstname || !req.body.lastname || !req.body.gender || !req.body.isTrainer) {
res.json({ success: false, msg: 'set up required fields' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password,
firstname: req.body.firstname,
lastname: req.body.lastname,
gender: req.body.gender,
isTrainer: req.body.isTraine
});
User.find({ email: req.body.email}, function(err, user){
if (err) {
res.send({ success: false, msg:'authentication error'})
}
else if (user.length != 0) {
res.send({success: false, msg:'Email already exists'})
console.log(user);
}else {
// save the user
newUser.save(function(err) {
if (err) {
console.log(err);
}else {
res.send({ success: true, msg: 'Your account created successfully! ' });
}
});
}
})
}
});
userRoutes.post('/signin', function(req, res) {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({ success: false, msg: 'Check your email' });
} else {
// check if password matches
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.sign(user, config.secret,{
expiresIn: 0
});
// return the information including token as JSON
res.json({
success: true,
token: token,
username: user.username
});
} else {
res.send({ success: false, msg: 'Check your password!' });
}
});
}
});
});
userRoutes.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
module.exports= userRoutes;
I want to secure the /user/users with the middle-ware so only user with token can access to. some suggestion please to do that or to change code structure
I would create a helper module that looks like this (e.g. auth.js):
module.exports=function(req,res,next){
//check user
if(valid){
next();
}else{
res.end("auth error");
}
};
So you can simply do this everywhere:
app.use("/top-secret",require("auth.js"));
app.get("/top-secret/main",...);
If you extend the helper module with some closures, it gets realy useful, e.g.:
module.exports.minLevel=function(level){
return function(req,res,next){
if(validUser && level<=user.level){
next();
}else{
res.end("auth error");
}
};
};
Use case
app.use("/admin",require("auth.js").minLevel(5));
I need help to figure this out. The update function is called to reset a password on database. I got this error.
TypeError: Cannot read property 'password' of undefined
module.exports.update = function (token, req, res) {
User.findOneAndUpdate({resetPasswordToken: token, password: req.body.password, resetPasswordExpires: {$gt: Date.now()}}, function(err) {
if (err) throw err;
return res.sendStatus(200);
console.log(User);
});
}
router.post('/forgot', function (req, res) {
var password = req.body.passwordnew;
var password2 = req.body.passwordnew2;
var update = User.update(password, password2, function (err, user) {
//userToken = token;
if (!update) {
console.log("token2 = " + req.params.resetPasswordToken);
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('forgot');
}
else {
user.save(function (err) {
user.password = password;
user.password2 = password2;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
});
console.log("save new password");
}
});
//}
})
when you use update method of mongoose 1st parameter will be query( by which you can find that doccument in collection) and 2nd will be what you want to update ..
So what query you make is not make sense , it will be like :
var userId=user; //mongoId
var newPassWord=req.body.passwordnew;
User.update({_id:userId}, {password:newPassWord}, callbackFunction);
this will update password of that perticular user.
Thanks
I'm making a simple webapp with facebook login.
If the facebook login button on my page is clicked,
FB.api(
'/me',
'GET',
{"fields":"id,name,birthday,gender"},
function(response) {
$.post('fb_login', response, "json");
}
);
is called, and a router handles '/fb_login' request; in the router the server checks the id of json object is already in its DB. If not, res.render('signup', ...) should be called.
However it didn't work. I already checked that res.render() was called, but the page 'signup.jade' didn't show up.
Here is my source code of router.
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '1012'
});
/* GET home page. */
router.post('/', function(req, res, next) {
var userid = req.body.id;
if (userid) {
pool.getConnection(function(err, connection) {
if (err) {
console.error('DB Connection error!!');
return;
}
console.log('DB Connection Success!!');
connection.query('use vasket');
connection.query('select count(*) result from user where userID=?',
[userid], function(err, result, field) {
var isAlreadyUser = result[0].result;
console.log(isAlreadyUser);
if (isAlreadyUser == 1) {
req.session.userid = userid;
res.redirect('/');
res.end();
console.log('DB FB Login Success!!');
connection.release();
}
else {
connection.release();
console.log('FIRST TIME!');
//This method was called, but the page rendered didn't
res.render('signup', {id: req.body.id, name: req.body.name, birthday: req.body.birthday, gender: req.body.gender});
}
});
});
} else {
res.redirect('/');
res.end();
}
How can I fix it?
To help debugging maybe you can modify your code like that :
// ... your code before
else {
connection.release();
console.log('FIRST TIME!');
console.log(req.body);
//This method was called, but the page rendered didn't
res.render(
'signup',
{
id : req.body.id,
name : req.body.name,
birthday: req.body.birthday,
gender : req.body.gender
} ,
function(err, html){
if(err) console.log(err);
console.log(html);
//res.send(html);
// trying same but forcing status
res.status(200).send(html);
}
);
}
});
});
} else {
res.redirect('/');
res.end();
}
This is an older question, but it's still in need of a solid answer. I had the exact same problem, but I think I've figured it out.
If the server's returning the proper response, that's not where your problem lies. jQuery (in the browser) will render the response, but you have to tell it to do so.
Here's what I had that was responding properly but not rendering:
$("#getsome").click(function() {
$.get("/task/create");
});
And here's how I got it to render:
$("#getsome").click(function() {
$.get("/task/create", function( data ) {
document.write(data);
});
});
Note that you may not need to replace the entire DOM like I'm doing.
References:
Replacing the entire
DOM
jQuery.get
I'm using Express 3.4.7 and mongo. I register a new character into my mongo database and then I would like to have my page (route : /game) but I want to get the data of the mongodb (like the _id) of my character.
Here is my code :
exports.newGame = function(ip, db){
return function(req, res){
//req.body return all the field
if(req.body.name && req.body.class) {
db.connect(dbconnection, function(err, db){
if(err) throw err;
var collection = db.collection('test'),
insertObj = {
name : req.body.name,
class : req.body.class
};
collection.insert(insertObj, function(err, data){
if(err) throw err;
console.log(data);
res.render('player/index', data); //Here is my problem
});
});
} else {
res.render('home/new', {title : 'Donjon & Gradon - New', ip : ip});
}
}
};
I would like to have the /game page and passing data and db after the query to mongo is OK.
I don't know if I am clear.
Can you help me ?
Regards,
Arnaud