I'm pretty new in node.js and I'm learning by my own, so I'm sorry if I ask stupid/easy questions.
I want to make a register form and insert the data into mongodb. I'm using express and mongoose to do that but I don't know how to insert the data in my database.
Here is what I've got:
My structure is:
Project
|--models
`--user.js
|--routes
`--api.js
|--www
`--register.html
|--server.js
package.json
The content is:
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var user = require('./models/user');
mongoose.connect('mongodb://localhost/Testdb');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', require('./routes/api'));
app.get("/register", function(req, res){
res.sendFile("register.html", { root: path.join(__dirname, './www')});
});
app.post("/register", function(req, res){
var u = new user();
u.firstname = req.body.firstname;
u.lastname = req.body.lastname;
u.locality = req.body.locality;
u.email = req.body.email;
u.password = req.body.password;
//here I get the parameters correctly but I don't now what to do with the user object to insert it in the database
});
app.listen(3000);
console.log('API is running on port 3000');
user.js
var restful = require('node-restful');
var mongoose = restful.mongoose;
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
firstname: String,
lastname: String,
locality: String,
email: {type: String, unique: true},
password: String
});
userSchema.pre('save', function(next) {
var user = this;
var shasum = crypto.createHash('sha1');
shasum.update(user.password);
user.password = shasum.digest('hex');
next();
});
module.exports = restful.model('Users', userSchema);
api.js
var express = require('express');
var router = express.Router();
var user = require('../models/user');
user.methods(['get', 'put', 'post', 'delete']);
user.register(router, '/users');
module.exports = router;
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><Document></Document></title>
</head>
<body>
<form action="/register" method="POST">
<label>Name</label><br/>
<input type="text" name="firstname"/><br/>
<label>Surname</label><br/>
<input type="text" name="lastname"/><br/>
<label>Locality</label><br/>
<input type="text" name="locality"/><br/>
<label>Email</label><br/>
<input type="text" name="email"/><br/>
<label>Password</label><br/>
<input type="password" name="password"/><br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
From postman when I do a POST to http://localhost:3000/api/users it works, but I want to do it when I submit the form and that's what I don't know how to do it. When I submit the form it reminds loading forever waiting to do something... how can I make a post of this data into de database from node.js?
Anyone can help me with this?
Thank you very much!
You need to call the DAO methods from the route handler and on callback from DAO method, you should send success or failure response to your client side.
For more information, you may look at -
This article
Hope this will help you
Thanks
Use this method:
db.collection.insert();
http://docs.mongodb.org/manual/reference/method/db.collection.insert/
Related
I am building a simple To Do application Using node js, express, mongodb and ejs.
My get Route renders the form and the post route handles post request on the form, they both work perfect, any time I insert a (todo) it gets saved and can be found in my Mongo compass.
But it does not appear on the screen as Todo App should be. It only prints out usual bullets of (ul). I don't know what I am doing wrong, here is my code:
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const session = require('express-session');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/Todo-App",
{useUnifiedTopology:true,useNewUrlParser:true,useFindAndModify:false,useCreateIndex:true});
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret:"secret"}));
var todoschema = mongoose.Schema({
item:String,
});
var Todo = mongoose.model("Todo",todoschema);
app.get('/',(req,res)=>{
res.render('home.ejs',{Todo:Todo});
});
app.post('/',(req,res)=>{
var newTodo = new Todo({
item:req.body.item,
});
newTodo.save((err,result)=>{
if(err){
throw err;
}
else{
res.redirect('/');
}
})
})
app.listen(8080,()=>{
console.log("App is running...")
})
Here is my code in the ejs file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>My To-Do Application</h1>
<form action="/" method="post">
<input type="text" name="item" placeholder="Enter Item">
<input type="submit" value="Add To List">
</form>
<%for(var i = 0; i < Todo.length; i++){%>
<li> <%=Todo[i]%></li>
<%}%>
</body>
</html>
I think the issue is here
app.get('/', (req, res) => {
res.render('home.ejs', { Todo : Todo });
});
you are doing the res.render without finding the documents from db
I think we need to add a find query before doing res.render
it should be something like that
app.get('/', (req, res) => {
Todo.find({}, (err, todos) => { // passing an empty object as a first argument to the find method means we need to get all the documents from Todo collection
if (err) {
throw err;
} else {
res.render('home.ejs', { Todo: todos });
}
});
});
hope it helps
I'm building a website, and i have a registration form where i need to submit a form via POST, and register a user in a mongoDB databse. The website works fine so far, but when i submit the registration form the browser just "waits for localhost" forever. I use EJS as my templating engine, although i don't think that matters.
register.ejs:
<% include partials/header %>
<%include partials/nav %>
<h1>REGISTER</h1>
Login
<form id="registerForm" action="/register" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<small id="passwordHelp" class="form-text text-muted">Your password must be at least 8 characters long.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% include partials/footer %>
app.js:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./models/user"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");
//Set up MongoDB
var mongo = require("mongo");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/customerapp';
//MongoJS
var mongojs = require("mongojs");
var db = mongojs("customerapp", ["users"]);
//Mongoose
var mongoose = require('mongoose');
mongoose.Promise = global.Promise
mongoose.createConnection("mongodb://localhost:27017/customerapp");
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "wah wah wah",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
var index = require("./routes/index");
var about = require("./routes/about");
var login = require("./routes/login");
//var register = require("./routes/register");
app.all("index", index);
app.all("about", about);
app.all("login", login);
//app.all("register", register);
// AUTH Routes
//Register get request
app.get("/register", function(req, res) {
res.render("register");
});
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username}),
req.body.password,
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
app.listen(process.env.PORT || 3000, process.env.IP, function () {
console.log('Example app listening on port 3000!')
})
You are using three params instead of two, use it like this.
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username,
password: req.body.password
}),
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
Check to make sure your versions of mongoDB and mongoose are compatible. You can find a compatibility chart here.
In addition to checking your MongoDB and mongoose versions, you should also check if it's actually connecting to the database by using a callback function when you connect to the server, like so:
//Connecting to database using mongoose.connect with a callback
mongoose.connect("mongodb://localhost:27017/customerapp", function(error) {
if(error) {
console.log("There was an error connecting to MongoDB.");
console.log(error);
} else {
console.log("Successfully connected to MongoDB!");
}
});
This callback may also work with mongoose.createConnection instead of mongoose.connect, but I haven't tried. If neither message prints to the console, then the app is not getting any response from the server, not even an error.
For some reason, as long as mongoDB is running at all, GET requests still seem to work even if the connection attempt hangs, but POST requests run into trouble.
Source: Mongoose never connects to mongodb
I am working on simple registration page using express and mongodb this is my html
<body>
<form>
<div align="center" ng-controller="regiCtrl">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" ng-model="user.userName" />
</td></tr>
<tr>
<td>Password :</td>
<td><input type="password" ng-model="user.password" />
</td></tr>
<tr>
<tr><td>
<input type="button" value = "Submit" ng-click="regi()"></td>
<td>
</td></tr>
</table>
</div>
</form>
</body>
and this is my controller
lyfee.controller('regiCtrl',['$scope','$http', function($scope,$http) {
$scope.user = {};
$scope.regi = function () {
// var data = {User: $scope.user }
console.log($scope.user);
$http.post('/regi',$scope.user);
console.log("post request send");
}
}]);
have a look of my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
//Used for open index.html by default(open html page which one will be in public folder)
app.use(express.static(__dirname + "/public"));
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: 'anystringoftext',
saveUninitialized: true,
resave: true}));
app.use('/', function(req, res){
//res.send('Our First Express program!');
//res.redirect('index.html');
//console.log(req.cookies);
// console.log(req.session);
console.log("HELLO WE ARE IN SERVER");
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lyfee_module');
console.log("Connection created");
var Userschema = require('./models/dbSchema');
app.post('/regi',function(req,res){
console.log("post request get");
/*
var schema = new Userschema();
schema.Firstname = req.body.Firstname;
schema.Lastname = req.body.Lastname;
schema.City = req.body.city;
schema.Email = req.body.email;
schema.Userid = req.body.userid;
schema.Password = req.body.password;
console.log(schema.Firstname);
// console.log(schema.Lastname);
*/
console.log(req);
var schema = new Userschema({
userName : req.body.userName,
password : req.body.password,
});
console.log(req.body);
console.log(schema);
schema.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Record Inserted', userName: req.body.userName, password: req.body.password});
});
});
app.listen(port);
console.log('Server running on port: ' + port);
it's my config.js
module.export = {
'secret' : 'lyfee',
'database': 'mongodb://localhost/lyfee_module'
};
and finally is my db
var mongoose = require('mongoose');
var User = new mongoose.Schema({
userName: String,
password: String,
});
//console.log(User);
module.exports = mongoose.model('user', User);
my entries is not storing in database even database with lyfee_module is not creating please help me, how to i can solve this problem ?
i think every thing is looking fine just add running port of mongodb in config.js like
mongodb://localhost:27017/
Have you tried using a callback with mongoose.connect()? I would recommend trying the following and see if you get any errors:
mongoose.connect(mongoUrl, err => {
console.log(err || `MongoDB connected at ${mongoUrl}`);
})
Iam not able to get the html page.My nodejs is connecting with mongodb but when iam getting values from html page the values are not storing in db.Iam not able establish the connection from frontend to db at a time.help me out
this is my login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="/" method="POST">
<center>
User Name: <input type="text" name="username"> <br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and this is my login.js code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/logindb';
var loginSchema = mongoose.Schema({
username: String,
password: String
});
mongoose.connect(url);
app.get('/login.html', function(req, res) {
res.sendFile(__dirname + "/" + "login.html");
})
app.post('/', function(req, res) {
var Book = mongoose.model('book', loginSchema);
var book1 = new Book({
username: req.body.username,
password: req.body.password
});
book1.save(function(err) {
if (err) throw err;
console.log("Login saved succesfully");
res.end('success');
}
);
});
app.listen(8000, function() {
console.log("Server is running!");
});
For using req.body.username you need to use body-parser module,
install: npm install body-parser -S
Code:
var express = require('express'),
app = express(),
bodyparser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Trying to post from a register form in a MEAN application, I can use Postman to successfully post using x-www-form-urlencoded, but the request body in the app is empty when I console.log it.
The register form (part):
<form class="form-horizontal" ng-submit="register.saveUser()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="user.userData.name">
api.js (part)
var bodyParser = require('body-parser'); // get body-parser
var User = require('../models/user');
var jwt = require('jsonwebtoken');
var config = require('../../config');
var superSecret = config.secret;
module.exports = function(app, express) {
var apiRouter = express.Router();
apiRouter.post('/register', function(req, res) {
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
console.log(req.body); //EMPTY
I have app.use bodyParser in server.js before the call to api.js
server.js (part)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var apiRoutes = require('./app/routes/api')(app, express);
app.use('/api', apiRoutes);
I'm doing something wrong but can't see what.
Added for #mscdex:
register.saveUser() refers to userRegisterController saveUser() function:
.controller('userRegisterController', function(User) {
var vm = this;
// function to create a user
vm.saveUser = function() {
vm.processing = true;
vm.message = '';
// use the register function in the userService
User.register(vm.userData)
.success(function(data) {
vm.processing = false;
vm.userData = {};
vm.message = data.message;
});
};
This uses the userService register function:
// register a user
userFactory.register = function(userData) {
return $http.post('/api/register/', userData);
};
This calls api file which I have posted above.
BTW when I use Postman the console.dir(req.headers['content-type']) shows 'application/x-www-form-urlencoded' and is successful.
I spent quite a few hours on this today and ultimately the problem of 'undefined' being received by the apiRouter function was due to my use of
<input type="text" class="form-control" ng-model="user.userData.name">
whereas I should have used
<input type="text" class="form-control" ng-model="register.userData.name">
because I had used
.when('/register', {
templateUrl: 'app/views/pages/register.html',
controller: 'userCreateController',
controllerAs: 'register'
});
in the apiRoutes file.
I'm still learning the usage of ControllerAs in this context.