I am trying an Example from Jump start node.js(chapterote 1 Authentication).I wrote all the program and created all the files and folders witch is needed for chapter 1.For those who dont know Chapter 1 is about using mongolab cloud Service.
form.html
<form action="/signup" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div><input type="submit" value="Sign Up"/></div>
</form>`
lib/db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports.mongoose = mongoose;
module.exports.Schema = Schema;
// Connect to cloud database
var username = "user"
var password = "password";
var address = ' #dbh42.mongolab.com:27427/nockmarket';
connect();
// Connect to mongo
function connect() {
var url = 'mongodb://' + username + ':' + password + address;
console.log('[*] not reaching here');
mongoose.connect(url);
}
function disconnect() {mongoose.disconnect()}
models/User.js
var db = require('../lib/db');
var UserSchema = new db.Schema({
username : {type: String, unique: true}
, password : String
})
var MyUser = db.mongoose.model('User', UserSchema);
// Exports
module.exports.addUser = addUser;
// Add user to database
function addUser(username, password, callback) {
var instance = new MyUser();
instance.username = username;
instance.password = password;
instance.save(function (err) {
if (err) {
callback(err);
}
else {
callback(null, instance);
}
});
}
When I sumbits the form app hangs and its not calling connect() function witch connects to the mongolab it just waits for finish but nothing happens.
thanks,
Related
Can anyone tell my why my login system isn't working on my server? it just returns user not found even though the users table in my mongo DB contains a valid username and password that I use. here is the code I use to try login.
app.post('/dologin', function (req, res) {
console.log(JSON.stringify(req.body))
var uname = req.body.username;
var pword = req.body.password;
db.collection('users').findOne({
"SignIn.username": uname
}, function (err, result) {
if (err) throw err;
if (!result) {
res.redirect('/SignIn');
console.log("user not found :(")
return
}
if (result.SignIn.password == pword) {
req.session.loggedin = true;
req.session.currentuser = uname;
res.redirect('pages/UserAccount')
console.log("a user was recognised, horay!")
} else {
res.redirect('/SignIn')
console.log("user not found :(")
}
});
});
this is the form used to take in the username and password it is stored in a file called SignIn.ejs:
<form action="/dologin" method="POST">
<input class="UsernameBox" type="text" placeholder="username" name="username">
<input class="PasswordBox" type="password" placeholder="password" name="password">
<button class="LogInButton" type="submit">login</button>
</form>
the MongoDB stores its username and passwords in a table called users
I need to get this going in the next day so any help would be greatly appreciated
I'm using Node for the first time and am having trouble when a certain response is triggered. In this case, I'm checking if the username and pw matches what I have in DynamoDB. It redirects to my page when the username and pw don't match my db, but when it does, all of my console.log output prints twice (which apparently has something to do with the favicon in Chrome) like "online" and "[pw] + database.js," but it also freezes my IDE and terminal. I then see the "The page isn't working, localhost didn't send any data" error in my browser. Ignore the privacy problems :) Thoughts?
database.js:
var myDB_lookup = function(username, password, route_callbck){
console.log('Looking up: ' + username);
users.get(username, function (err, data) {
if (err) {
route_callbck(null, "Lookup error: "+err);
} else if (data == null) {
route_callbck(null, null);
} else {
// JSON object that stores password & fullname
var value = JSON.parse(data[0].value);
var pw = value.password;
if (pw.valueOf() == password.valueOf()){
route_callbck({ password : pw }, null);
console.log(pw + "database.js");
}else{
//console.log('wrong password');
route_callbck(null, null);
}
}
});
};
routes.js:
var checkLogin = function(req,res){
var user = req.body.username;
var pw = req.body.password;
console.log(user + pw + "routes");
db.lookup(user, pw, function(data, err) {
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}
});
};
main.ejs:
<form method="post" action="/checklogin">
Enter username here: <br>
<input type="text" name="username" placeholder = "Your username"> <br>
Enter password here: <br>
<input type="password" name="password" placeholder = "Your password">
<input type="submit" value="Log In">
</form>
The functions are all linked up in routes.js when I do module.exports = ...
You probably forget to send the response, make sure
res.render() or res.json() or res.send() gets hit
you should put a try/catch around JSON.parse(), that's a best practice.
Looks like your culprit is here:
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
// you need to send the response here too! <<<<<
res.render('main.ejs'); //// !!!
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}
Whenever I submit a form with information it is returned as undefined. I have posted the code below. If I include the (enctype="multipart/form-data") in my form I dont receive anything for the body (req.body). However, if I dont include it I receive a body but the file processing does not work and the page just keeps loading.
app.post('/processupload', function(req, res) {
var date = new Date();
titles.push(req.body.pTitle);
descriptions.push(req.body.postDescription);
dates.push(date.toString());
file_names.push(req.body.fUpload);
console.log(req);
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files)
{
if(err) return res.redirect(303, '/error');
});
form.on('end', function(fields, files)
{
var temp_path = this.openedFiles[0].path;
var file_name = this.openedFiles[0].name;
var new_location = __dirname + '/public/images/';
fs.copy(temp_path, new_location + file_name);
res.redirect(303, 'home');
});
});
<form action="/processupload" enctype="multipart/form-data" method="POST" id="uploadForm" name="postForm">
<p align="center" id="pUploadForm" name="pPostForm"><label for="photoTitle">Photo Title: </label>
<input type="text" id="photoTitle" name="pTitle"><br>
<br><input type="file" id="fileUpload" name="fUpload"><br>
<br><label for="photoCaption">Photo Caption: </label><br>
<textarea rows="10" cols="50" id="photoCaption" name="postDescription"></textarea><br><br>
</p>
</form>
I created a project few weeks back that had photo upload. I used Angular and Node. But it should still work without Angular only using Node. I used multer npm package.
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var multer = require('multer');
var upload = multer({ storage: multer.memoryStorage() }); //Save photo in memory
router.post('/processupload', upload.single('photo'), function(req, res, next){
var bucketName = process.env.BUCKET_NAME;
var file = req.file;
var filename = file.originalname;
var ext = _.last(filename.split('.'))
var keyName = uuid.v4() + '.' + ext;
var url = process.env.AWS_URL + bucketName + '/' + keyName;
var params = { Bucket: bucketName, Key: keyName, Body: file.buffer, ACL: 'public-read' };
s3.putObject(params, function(err, data) {
if (err){
return res.status(400).send(err)
} else{
console.log("Successfully uploaded data to myBucket/myKey");
console.log("The URL is", url);
res.send(url)
}
});
});
This helped me uploading images then gives me back the image url from the S3 Bucket. But you can handle that file as you want. Multer allows you to access to req.file so you can do whatever you need to do, in this example I created a unique id in order to get a url to send back to the front-end and therefore use it a source somehow. This is a form working with this code:
<form action="/testupload" method='post' enctype='multipart/form-data'>
<input type="file" name="photo" id="photo" multiple=false>
<button type="submit">Submit</button>
</form>
Something important that took a long time to debug though the name="photo" in the form must be reflected by the upload.single('photo') middleware. I hope this helps, there are so many ways go around this, this is just one.
Sources:
https://www.npmjs.com/package/multer
http://docs.aws.amazon.com/AmazonS3/latest/UG/UploadingObjectsintoAmazonS3.html
Users will be able to either send a text post(input type="text") or image post(input type="file"). But they won't be sending both
Here's my form (in Jade):
form#addPost(action="/uploads", method="post", placeholder='Add your ideas here...')
input#postinput(type="text", name="contents" placeholder="Add your ideas here...")
div.privacy(class="onoffswitch", id='privacytog')
input(type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked)
label(class="onoffswitch-label" for="myonoffswitch")
span(class="onoffswitch-inner")
span(class="onoffswitch-switch")
<div style="height:0px;overflow:hidden">
<input type="file" id="fileInput" name="fileInput" accept="image/*">
</div>
input#submit1(type="submit", value="Post")
And Here's my app.js(server-side code)
var util = require("util");
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require("multer");
app.use(multer({
dest: "./public/uploads/"
}));
app.post("/uploads", function(req, res) {
var data = req.body;
var id = req.user._id;
var username = req.user.username;
var date = Date();
var onOff = false;
if (req.body.onoffswitch) {
onOff = true;
}
//Images upload to uploads folder
if (req.files) {
console.log(util.inspect(req.files));
if (req.files.fileInput.size === 0) {
return next(new Error("Hey, first would you select a file?"));
}
fs.exists(req.files.fileInput.path, function(exists) {
if(exists) {
res.end("Got your file!");
} else {
res.end("Well, there is no magic for those who don’t believe in it!");
}
});
}
User.findById(id, function(err, user) {
if (err) return handleErr(err);
var uid = shortid.generate();
newPost = {
//If sending down an Image use data.fileInput not contents
contents: [data.contents || '/img/'+data.fileInput],
_id: uid,
privacy: onOff,
username: req.user.username,
date: date,
rating: Number(0),
uwv: []
};
user.posts.push(newPost);
user.save(function(err, user){
if(err) return handleErr(err);
if(newPost.privacy === 'false'){
for (var i = 0; i < user.followers.length; i++) {
User.findOne({username:user.followers[i]}, function(err, follower){
follower.discover.push(newPost)
follower.save();
});
}
}
});
});
}
Images are being uploaded and saved to uploads folder. However when posting just a text post(only filling in input type="text") it keeps throwing back the error: Cannot read property 'size' of undefined
Typically browsers will not send the file field if there is no file selected, so there is no way for the backend to know that there was such a field.
Instead just check for the existence of the file field: if (!req.files.fileInput). You may also want to check that the file is not empty: if (!req.files.fileInput || !req.files.fileInput.size)
I have a form. I need to get text from my form to save it in MongoDB.
tweets.ejs:
<form method="post" action="/tweets">
<input type="text" id="txt" name="text"/>
<input type="button" id="btn" value="Touch me">
</form>
Here is my route file tweets.js:
var Message = require('models/messages');
exports.get = function(req,res) {
res.render('tweets')
};
I use mongoose schema(models/messages.js):
var mongoose = require('../libs/mongoose'),
Schema = mongoose.Schema;
var MessageSchema = new Schema({
message: String,
date: Date
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
I tried set var m = req.body.text in tweets.js, but I think it's absolutely wrong way
exports.post = function(req,res){
var m = new Message;
m.message = req.body.text;
m.save(); }
Explain me how to do it right please!
in your routes or app file route should be
var tweets = require("tweets");
app.post("/tweets", tweets.post);
in your tweets.js file
var Message = require('models/messages');
exports.post = function(req,res){
console.log(req.body.text)
var msg = {message:req.body.text,date:new Date()};
Message(msg).save(function(error,data){
if (data){
console.log("Save "+ JSON.stringify(data));
res.send({statud:"OK",msg:data})
}
else{
res.send({statud:"Cancel"})
}
});
}