Cannot complete GET request - javascript

I'm attempting to create a form to collect email addresses. The email address POSTs to /dreamjob.
When I try to access the list on /emails no error shows up but the page does not load & times out. I cannot figure out the issue. How would I change my code to correct this? Thank you!
router.post("/dreamjob", function(req, res){
//Create Email
Email.create(req.body.email, function(err, newEmail){
if(err){
res.render("station.ejs");
} else {
newEmail.save();
console.log(req.body.email)
}
});
});
//All Emails:
router.get("/emails", function(req, res){
Email.find, function(err, email){
if (err){
console.log("ERROR!");
} else {
res.render("emails", {Email: email});
}
}
});
Model:
var mongoose = require("mongoose");
var emailSchema = new mongoose.Schema({
email: String
});
module.exports = mongoose.model("Email", emailSchema);

When you create an email, you're only responding to the request in case of error, try something like this:
Email.create(req.body.email, function(err, newEmail){
if(err){
res.render("station.ejs");
} else {
newEmail.save();
console.log(req.body.email);
res.send(200); // reply to the http request here
}
});

Related

how do I restrict users to only one post request

I'm making a friend finder application. I want to restrict the users to only one post. Here's what I have so far:
router.post("/", middleware.isLoggedIn, (req, res) => {
//get data from form and add to friendfinder array
var rank = req.body.rank;
var discord = req.body.discord;
var valorantid = req.body.valorantid;
var author = {
id: req.user._id,
username: req.user.username,
};
var newFriend = {rank:rank, discord:discord, valorantid:valorantid, author:author};
//create a new friend finder entry
Lookinglist.create(newFriend, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to frinedfinder page
res.redirect("friendfinder");
}
});
});
Do you have a route for /friendfinder?
if yes, use this
res.redirect("friendfinder");

Node JS MySQL Authentication

I am new to node JS. I am working on authenticating users against backend MYSQL.
Here is the code snippet of authentication
function Authenticate(username, password, fn) {
connection.connect();
var user;
connection.query('SELECT * from Users where username = ' +
connection.escape(username) + ' and password =' + connection.escape(password),
function(err, rows) {
user = rows[0].username;
});
if (!user) {
return fn(new Error('cannot find user'));
} else {
return fn(null, user);
}
connection.end();
}
This is my call back function.
app.post('/Login', function(req, res) {
Authenticate(req.body.username, req.body.password, function(err, user) {
if (user) {
req.session.regenerate(function() {
req.session.user = user;
req.session.success = 'Authenticated as ' + user;
res.redirect('Home');
});
} else {
req.session.error = 'Authentication failed, please check your username and password.';
res.redirect('Login');
}
});
})
I am getting an error, which i cannot get my head around.
TypeError: Cannot set property 'error' of undefined
at /...../.../node_modules/app.js:42:23
at Authenticate (/..../..../node_modules/app.js:82:11).
Please share your thoughts!
Takes the else out and see if any other req.session functions properly if not check if middleware is configured correctly for express validator

how to redirect using pure javascript in an express application

I have a node.js/express/mysql/angular.js application and I'm trying to redirect a user after they login, on the server side. This is the server-side controller and I cannot figure out how to redirect the user to another page. Ive tried res.render, res.redirect, window.location.href with no success. Errors I'm getting with res.render() are 'No default engine was specified and no extension was provided.' window.location.href says window is undefined. And res.redirect() allows me to console.log the html of the page I want to direct too. Any help is greatly appreciated, Thanks!
var Query = require('./../models/query.js');
module.exports = (function(){
return {
show: function(req,res) {
req.getConnection(function(err,connection){
connection.query('SELECT * FROM users',function(err,rows){
res.json(rows);
});
});
},
add: function(req,res){
var newUser = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created_at: req.body.created_at
};
var table = "users";
Query.insert(req,newUser,table,function(err,results){
if(err) return res.json(err);
Query.find(req,table,function(err,results){
if(err) return res.json(err);
res.json(results);
});
});
},
login: function(req,res) {
var input = req.body;
console.log("got here", input);
req.getConnection(function(req, connection) {
// console.log("got connections",connection);
connection.query('SELECT * FROM users WHERE email = ?',input.email, function(err, rows) {
if (err) {
console.log("User doesn't exist: %s", err);
res.redirect('/', { data:"failed"});
} else {
if (input.password == rows[0].password) {
console.log("User password is matched");
*** success redirect right here ****
res.redirect('/static/taxonomer'+'.html');
} else {
console.log("failed here", rows[0].password);
res.redirect( '/', { data:"failed"});
}
}
});
});
}
};
})();
Without seeing your routes I am guessing that login method on the above controller corresponds to a POST route. For example,
app.post('some/login/route', theAboveController.login)
Therefore, the redirect is controlled on the client side.
So, make then following changes:
1) Use res.send to send a redirect url as a string to the client. For example,
res.send('/static/taxonomer'+'.html')
2) Then on the client side in your success callback, change the location to the url you received from the res.send method. For example,
$http.post('/some/login/route', data).then(function(response) {
$window.location.href = response;
}, errorCallback);
Express's docs are pretty good here: http://expressjs.com/api.html#res.redirect
res.redirect('https://stackoverflow.com'); will redirect them to that specific URL.
res.redirect('/foo'); will redirect to a specific URL
res.redirect('back'); will redirect to the referrer. So you can do something like a middleware that redirects to /login and then the login finishes successfully and it goes back to the original path.

req.session don't set with post request

I am newby in node.js and I try to implement the simplest authorization in Express. I want to set req.session.userId to users id from database. I can get user id from database using simple form and post request, but I can't set req.session.userId . The most incomprehensible thing for me - why sometimes req.session is working and sometimes is not.
My code for explanation.
in app.js:
Configure segment:
app.use(express.session({secret: 'asdads', key: 'sid', cookie: { maxAge: 600000, httpOnly: false }}));
After that I handle POST request with:
app.post('/login', routes.authorize);
My routes.authorize:
exports.authorize = function(req, res){
if(req.body){
var login = req.body.login;
var password = req.body.password;
//gET USER FROM DATABASE
db.getUser(login, password, function(err, results){
//ensure that results is correct
console.log(results);
if(err){ res.send("User not found", 500); return;}
//PLACE WITH BUG :)
req.session.userId = results[0].id;
});
}
res.render('login', { title: 'Express!' });
}
I think I couldnt set req.session.userId in this place because I access here via POST. If I am right please help me to get access to req.session in this place.
Thanks in advance.
I think the problem is that you're immediately responding to the request before your db.getUser() completes. IIRC the Express session middleware saves session changes when the response is sent, so try something like this instead:
exports.authorize = function(req, res) {
if (!req.body)
return res.render('login', { title: 'Express!' });
var login = req.body.login;
var password = req.body.password;
db.getUser(login, password, function(err, results) {
if (err)
return res.send("User not found", 500);
req.session.userId = results[0].id;
res.render('login', { title: 'Express!' });
});
}

Node.js Typeerror connect-flash

I'm having trouble showing flash messages with Node.js, Express and Connect-Flash.
I can show error messages for example, but if I want to send more than one message (e.g. a success message if an update was successful or an error message if there was a problem with the update) then I have problems.
Here's the error:
http://www.evernote.com/shard/s15/sh/5160abda-ddac-405c-9ea5-3563f3c39a02/7576bce006e47a8b1ea0346472996550
And here's snippets of my code:
// Routes.js
// ======================================
// CHANGE PASSWORD
// ======================================
app.get('/password', isLoggedIn, function (req, res) {
res.render('password', {
user: req.user, // get the user out of session and pass to template
error: req.flash('error'),
success: req.flash('success')
});
});
app.post('/password', isLoggedIn, function (req, res) {
// Save settings
if (req.body.newPassword == req.body.confirmNewPassword) {
User.findOne({_id: req.user._id}, function (err, user) {
user.local.password = generateHash(req.body.newPassword);
user.save(function(err) {
if (err)
throw new Error('There was a problem saving the password');
req.flash('success', 'Password updated successfully')
req.user = user;
res.redirect('password');
});
});
} else {
req.flash('error', 'Passwords did not match');
res.redirect('password');
}
});
// Jade template
// ===================
- if (error) // GET ERROR ON THIS LINE <------------
div.alert.alert-warning #{error}
- elseif (success)
div.alert.alert-success #{success}
Thank you!
I've fixed the problem. Here's what I did:
routes.js
// ======================================
// CHANGE PASSWORD
// ======================================
app.get('/password', isLoggedIn, function (req, res) {
var flash = req.flash();
res.render('password', {
user: req.user,
flash: flash
});
});
password.jade
if flash.error
div.alert.alert-danger #{flash.error}
else if flash.success
div.alert.alert-success #{flash.success}

Categories

Resources