I'm trying to build a basic registration page using node.js, express, mongoDB and AngularJS.
Before I tried to implement this registration functionality, I was using Angular routing for my views.
See the contents of my app.routes file below...
angular.module('app.routes', [])
.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/Login.html"
})
.when("/Register", {
templateUrl: "views/Register.html"
})
.when("/Home", {
templateUrl: "views/Home.html",
controller: "homeController"
})
.when("/CocktailDetails", {
templateUrl: "views/CocktailDetails.html",
controller: "cocktailDetailsController"
})
.when("/Favourites", {
templateUrl: "views/Favourites.html",
controller: "favouritesController"
})
.otherwise({
redirectTo: "/"
})
})
When the app loads it will direct the user to a login page, if they don't have an account there's a link to go the register page, url for this page is http://localhost:3000/#!/Register.
Please see view for the Register page below...
<div class="main">
<p class="sign" align="center">Register</p>
<form class="form1" action="/Register" method="POST">
<input class="un " type="email" align="center" placeholder="Email" name="username" required>
<input class="pass" type="password" align="center" placeholder="Password" name="password" required>
<a class="submit" align="center">Register</a>
</div>
So when they click the submit link/button it will perform a POST request, to create a new user in the userDB.
Please see server.js file content below...
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(express.static('node_modules'));
app.use(express.static('public'));
mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
const userSchema = {
email: String,
password: String
};
const User = new mongoose.model("User", userSchema);
//Routes
app.get("/", function (req, res) {
res.render("Login");
});
app.get("/Register", function (req, res) {
res.render("Register");
});
app.get("/Home", function (req, res) {
res.render("Home");
});
app.get("/CocktailDetails", function (req, res) {
res.render("CocktailDetails");
});
app.get("/Favourites", function (req, res) {
res.render("Favourites");
});
app.use(router);
const port = 3000;
app.listen(port);
console.log('Server is running on port 3000');
//POSTS
app.post("/Register", function (req, res) {
const newUser = new User({
email: req.body.username,
password: req.body.password
});
newUser.save(function (err) {
if (err) {
console.log(err);
} else {
res.render("Home")
}
});
})
I've mirrored my angular routes for the express routes.
But when I click the register button, nothing happens, checking the console, no errors but no POST request is made.
What am I missing here? I've tried changing the gets in the server.js but no luck.
I'm wondering if it's got something to do with the fact angular is putting #! on the url for each view.
Do I need to set HTML5 mode to true in my angular route file?
My file structure for the views is public > views.
For now I'm just trying to get a basic username and password into the database, I will look at implementing passport and encryption at a later stage.
Related
I am stuck with this code. I want to insert three fields in my database using User.register(), but my passport.authenticate() is giving me bad request and redirect me to register page again and again, but my data got inserted into the database.
Here is my app.js:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.set("view engine", 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.set("strictQuery", true);
mongoose.connect("mongodb://127.0.0.1:27017/My1stProjectDb", (err) => {
if (err) {
console.log(err);
} else {
console.log("Success !!!");
}
});
const userSchema = new mongoose.Schema({
name: String,
email: String,
Password: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/sell", function (req, res) {
res.render("sell");
});
app.get("/categories", function (req, res) {
res.render("categories");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/login", function (req, res) {
res.render("register")
})
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets")
} else {
res.render("register")
}
});
app.get("/logout", function (req, res) {
req.logout((err) => {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
app.post("/register", function (req, res) {
const registerUser = new User({ email: req.body.useremail, username: req.body.username });
User.register(registerUser, req.body.userpassword, function (err, user) {
if (err) {
console.log(err);
} else{
passport.authenticate("local",{ failureRedirect: '/register' })(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function () {
console.log("Server started at port 3000");
});
Here is registration page
<form action="/register" method="POST">
<div class="form sign-up">
<h2>Create your Account</h2>
<label>
<span>Name</span>
<input type="text" name="username" />
</label>
<label>
<span>Email</span>
<input type="email" name="useremail" />
</label>
<label>
<span>Password</span>
<input type="password" name="userpassword"/>
</label>
<button type="submit" class="submit">Sign Up</button>
</div>
</form>
I want to make my code compatible for three fields entry in userSchema into database and successfully redirect it to secrets page with authentication.
I am trying to build a website that allows a user to add a collectors item to the website. It has a form that requires certain fields to be filled out (I chose Funko Pop's). I have got everything working for the exception of having the image uploaded to the index.hbs page and into the MongoDB database.
Can anyone help? I think I am very close, but my terminal is throwing a Mongoose validator error (I'll show this at the end of the post)
The image seems to be sent to my "uploads" folder successfully, it just seems that there is some miscommunication happening with MongoDB because mongoose isn't happy.
Would anyone know what the issue is? And know how to fix it?
Thank you all for the help!
Here is my code:
Collection.js Controller/Route:
const express = require('express')
const router = express.Router()
const Collection = require('../models/collection')
const globalAuthFunction = require('./authenticationFunction')
const multer = require('multer')
// storage for multer
const storage = multer.diskStorage({
destination: function(err, file, callback){
callback(null, './public/uploads')
},
filename: function(req, file, callback){
callback(null, Date.now() + file.originalname)
}
})
const upload = multer({
storage: storage
})
router.get('/', (req, res) => {
Collection.find((err, collections) => {
if (err) {
console.log(err);
}
else {
res.render('collections/index', {
title: 'Collections',
collections: collections,
user: req.user
})
}
})
})
router.get('/create', globalAuthFunction.isAuthenticated, (req, res) => {
Collection.find((err, collections) => {
if(err){
console.log(err)
}
else{
res.render('collections/create', {
title: 'Add Employer',
collections: collections,
user: req.user,
})
}
})
})
router.post('/create', upload.single('image'), globalAuthFunction.isAuthenticated, (req, res) => {
Collection.create(req.body, (err, newCollection) => {
if (err) {
console.log(err)
}
else {
res.redirect('/collections')
}
})
})
router.get('/edit/:_id', globalAuthFunction.isAuthenticated, (req, res) => {
Collection.findById(req.params._id, (err, collection) => {
if(err){
console.log(err)
}
else{
res.render('collections/edit', {
title: 'Funko Pop Details',
collection: collection,
user: req.user,
image: req.file.filename
})
}
})
})
router.post('/edit/:_id', globalAuthFunction.isAuthenticated, (req, res) => {
Collection.findByIdAndUpdate({ _id: req.params._id}, req.body, null, (err, collection) =>{
if(err){
console.log(err)
}else{
res.redirect('/collections')
}
})
})
router.get('/delete/:_id', globalAuthFunction.isAuthenticated, (req, res) => {
Collection.deleteOne({ _id: req.params._id}, (err) => {
if(err){
console.log(err)
}
else{
res.redirect('/collections')
}
})
})
module.exports = router
My create.hbs:
<h1>Add a Funko Pop to Your Collection</h1>
<form method="post" enctype="multipart/form-data">
<fieldset>
<label for="character" class="col-2">Character: *</label>
<input name="character" id="character" required />
</fieldset>
<fieldset>
<label for="mediaTitle" class="col-2">Move or Television Name: *</label>
<input name="mediaTitle" id="mediaTitle" required />
</fieldset>
<fieldset>
<label for="category" class="col-2">Category: *</label>
<input name="category" id="category" required />
</fieldset>
<fieldset>
<label for="popNumber" class="col-2">Funko Pop Number: *</label>
<input name="popNumber" id="popNumber" required />
</fieldset>
<fieldset>
<label for="specialtySticker" class="col-2">Specialty Sticker: </label>
<input name="specialtySticker" id="specialtySticker" placeholder="N/A if there is no sticker"/>
</fieldset>
<fieldset>
<label for="price" class="col-2">Price: *</label>
<input name="price" id="price" required />
</fieldset>
<fieldset>
<label for="releaseYear" class="col-2">Funko Pop Release Year: *</label>
<input name="releaseYear" id="releaseYear" required />
</fieldset>
<fieldset>
<label for="image" class="col-2">Upload Image:</label>
<input type="file" name="image" id="image" value="image"/>
</fieldset>
<button class="btn btn-primary offset-2">Save</button>
</form>
My index.hbs:
<h1>Funko Pop Collection</h1>
{{#if user}}
<a class="btn btn-secondary" href="/collections/create">Add a Funko Pop</a>
{{/if}}
<section class="row">
{{#each collections}}
<div class="card col-2 m-2">
<div class="card-body text-center h-100">
<img src="{{this.image}}"/>
<h5 class="card-title">{{this.character}}</h5>
<p>Funko Pop Title: {{this.mediaTitle}}</p>
<p>Category: {{this.category}}</p>
<p>Pop Number: {{this.popNumber}}</p>
<p>Specialty Sticker: {{this.specialtySticker}}</p>
<p>Value: ${{this.price}}</p>
<p>Year:{{this.releaseYear}}</p>
{{#if ../user}}
<div>
Edit
Delete
</div>
{{/if}}
</div>
</div>
{{/each}}
</section>
My app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./controllers/index');
var usersRouter = require('./controllers/users');
const collections = require('./controllers/collections')
const auth = require('./controllers/auth')
const passport = require('passport')
const session = require('express-session')
const multer = require('multer')
var app = express();
// database connection to MongoDB
if (process.env.NODE_ENV !== 'production'){
require('dotenv').config()
}
app.use(session ({
secret: process.env.PASSPORT_SECRET,
resave: true,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
const User = require('./models/user')
passport.use(User.createStrategy())
// let passport read/write user data to/from session vars
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())
const google = require('passport-google-oauth20').Strategy
passport.use(new google({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL
},
(accessToken, refreshToken, profile, done) => {
User.findOrCreate({ oauthId: profile.id}, {
username: profile.displayName,
oauthProvider: 'Google',
created: Date.now()
}, (err, user) => {
return done(err, user)
})
}
))
const mongoose = require('mongoose');
const { access } = require('fs');
mongoose.connect(process.env.DATABASE_URL)
.then(
(res) => {
console.log('Connected to MongoDB')
}
).catch(() => {
console.log('Cannot connect to MongoDB')
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/collections', collections)
app.use('/auth', auth)
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is what my terminal is showing when I try and create a new Funko Pop Object in MongoDB:
It is saying there is an incorrect path or something. The image is uploading correctly to my "uploads" folder, it just seems to be having an issue with the database connection.
I thought it may be that the image type in my model was wrong, so I switched it to "Buffer" instead of "String", but it still showed me the same exact error. I have watched several tutorials, but they have set it up completely different than mine.
They seem to be using a something like this in there "post" function in there controllers:
let connection = new Connection({
title: request.body.title,
img: request.file.filename
}
I do not know enough about handlebars, MongoDB or Multer to be able to diagnose the issues that is happening. Any help would be greatly appreciated.
Thank you!
since you are using multer, change it from request.file.filename to request.file.path
This is my first web dev project. I am basically trying to make a simple website to sell light sabers. The goal is to be able to create an account, login, add, edit and delete light sabers. Be able to add them to cart and checkout. I am using node.js, express, and mongoDB in visual studio code. I am also learning github throughout the process. As of now I have the layout of the website mostly set up. Am able to create accounts and login. I am currently stuck on creating items(light sabers) and saving them in the mongoDB database. Specifically my http methods in the routes/items files are not working, they were working previously in the app.js file but I decided to move everything for organizational purposes. Again, this is my first time working with any of this tech and this project is a work in progress, any input is appreciated. Thanks.
Here is my code: There is a lot of code not being used and its kind of a mess. I know..
app.js file:
const express = require("express");
const session = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require('body-parser');
var localStrategy = require('passport-local');
var passportLocalMongoose = require("passport-local-mongoose");
var router = express.Router();
const app = express();
const indexRouter = require('./routes/index')
const itemsRouter = require('./routes/items')
//npm install ejs body-parser mongoose passport passport
var uri = "mongodb://username:password#cluster0-shard-00-00-
hnxfk.mongodb.net:27017,cluster0-shard-00-01-
hnxfk.mongodb.net:27017,cluster0-shard-00-02-
hnxfk.mongodb.net:27017/test?
ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority";
var localHost = "mongodb://localhost:27017/Project2SamJoshEricRoy"
mongoose.connect(uri,{useNewUrlParser: true, useUnifiedTopology:
true });
var User = require('./models/user');
var Item = require('./models/item');
// var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(require('express-session')({
secret: "application secret shhhh",
resave: false,
saveUninitialized: false
}));
passport.use(new localStrategy(User.authenticate()))
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter)
app.use('/items', itemsRouter)
//create account
app.get("/createAccount",(req,res)=> {
res.render("createAccount");
});
app.get('/createAccount', function(req,res) {
res.render('createAccount');
});
app.post("/createAccount",(req,res)=> {
req.body.username;
req.body.password;
User.register(new
User({username:req.body.username}),req.body.password,
(err,user) =>{
if(err) {
console.log(err);
return res.render("createAccount");
}
passport.authenticate("local")(req,res,() => {
res.redirect('/login');
console.log(req.body.username
+ " " + req.body.password);
console.log(user);
});
});
});
//login
app.get("/login",(req,res) => {
res.render("login")
User.find(function(err,users) {
if(err) {
console.log(err);
}
// console.log(users);
})
});
app.post('/login',passport.authenticate("local",{
successRedirect: "/lightsabers",
failureRedirect: "/login"
}),(req,res)=> {
});
function isLoggedIn(req,res,next) {
console.log("CALL")
if(req.isAuthenticated()) {
console.log("logged in ");
return next();
}
res.redirect("/login");
console.log("error logging in");
}
//logout
app.get("/logout",(req,res)=> {
req.logout();
res.redirect('/');
});
//lightsabers
//app.get("/lightsabers",isLoggedIn,(req,res)=> {
//res.render("lightsabers",{user: req.user});
//console.log(req.user);
//});
//shopping cart
app.get("/cart",(req,res)=> {
res.render("cart");
});
app.get('/createLightsaber',(req,res)=> {
res.render("newItem",{user:req.User});
console.log("user is with us");
console.log(req.user)
});
app.get('/updateItem',(req,res)=> {
res.render("updateLightsaber");
});
app.get('/deleteLightsaber',(req,res)=> {
res.render("updateLightsaber");
});
/routes/index.js file:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('index')
})
module.exports = router
routes/items.js
const express = require('express')
const router = express.Router()
const Item = require('../models/item')
//display page
router.get("/",(req,res)=> {
res.render("newItem");
});
// all items route
router.get('/', async (req, res) =>{
try{
const items = await Item.find({})
res.render('items/newItem', {item: new Item() })
} catch {
res.redirect('/')
}
})
//new item route (display form)
router.get('/newItem', (req, res) => {
res.render('items/newItem', {item: new Item() })
})
// create new item route (actual creation)
router.post('/newItem', async (req,res) => {
const item = new Item({
color:req.body.color,
price:req.body.price,
link:req.body.link
})
try{
const newItem = await item.save()
res.redirect('lightsabers')
} catch {
res.render('items/newItem', {
item: item,
errorMessage:'Error creating item'
})
}
})
/update item
app.get("/updateItem",(req,res)=> {
res.render("updateItem");
});
module.exports = router
newItem.ejs
<!DOCTYPE html>
<html>
<head>
<title> </title>
<link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h1> Adding New Item </h1>
<form action="/items" method="POST">
<h2>
Color: <input type="text" name="color"><br>
Price: <input type="text" name="price"><br>
Image Link:<input type="text" name="link"><br>
<br><br>
<button id="addItem">Add Item</button>
<%= typeof(message) != "undefined"?message:"" %>
</h2>
</form>
<form action="/lightsabers">
<h2><button> Back </button></h2>
</form>
<script type="text/javascript" src="../public/app.js">
</script>
</body>
</html>
If you wish to see any other parts of the code let me know. I may be forgetting something important.
I'm new to the MERN stack and backend programming. I have a React form that I want to submit to an MLab database using Express. I am unable to successfully POST the form data to the database. I'm not sure if I'm taking the correct approach or not. My form is working and I am able to log the fields, I run into problems when trying to do a POST request to submit the form data.
Here is my form:
import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, FormGroup, Label, Input } from 'reactstrap';
class AddBookModal extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: false,
bookTitle: '',
author: '',
genre: ''
};
this.toggle = this.toggle.bind(this);
this.onSubmit = this.handleSubmit.bind(this);
}
toggle() {
this.setState(prevState => ({
modal: !prevState.modal
}));
}
handleSubmit = (event) => {
event.preventDefault();
const data = this.state;
//console.log("Data from form :" + data.bookTitle, data.author, data.genre);
}
handleInputChange = (event) => {
event.preventDefault();
this.setState({
[event.target.name]:
event.target.value
});
}
render() {
const {bookTitle} = this.state;
const {author} = this.state;
const {genre} = this.state;
return (
<div>
<Button id="add-book-button" onClick={this.toggle}>Add Book</Button>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>Add Book</ModalHeader>
<ModalBody>
<Form method="POST" action="/profile" id="add-book-form" onSubmit={this.handleSubmit} >
<FormGroup>
<Label for="book-title-label">Book Title</Label>
<Input
value={bookTitle}
name="bookTitle"
onChange={this.handleInputChange}
placeholder="Enter name of book" />
</FormGroup>
<FormGroup>
<Label for="book-author-label">Author</Label>
<Input
value={author}
name="author"
onChange={this.handleInputChange}
placeholder="Enter author of book" />
</FormGroup>
<FormGroup>
<Label for="exampleSelect">Genre</Label>
<Input
onChange={this.handleInputChange}
value={genre}
type="select"
name="genre"
id="exampleSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</Input>
</FormGroup>
<ModalFooter>
<Button color="primary" type="submit" onClick={this.toggle}>Submit</Button>{' '}
<Button color="secondary" onClick={this.toggle}>Cancel</Button>
</ModalFooter>
</Form>
</ModalBody>
</Modal>
</div>
);
}
}
export default AddBookModal;
Here is my Express route:
const router = require('express').Router();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// localhost:3000/profile
// User Model
const User = require('../../models/user-model');
const Book = require('../../models/book-model');
// Checks if user is not logged in
const authCheck = (req, res, next) => {
if(!req.user) {
// If user is not logged in, redirect them to login page
res.redirect('/auth/login');
}
else {
// If user is logged in call next in router.get
next();
}
};
router.get('/', authCheck, (req, res) => {
res.send('you are logged in, this is your profile : ' + req.user);
});
router.post('/', urlencodedParser, (req, res) => {
console.log(req.body);
const newUser = new User({
name: req.body.name,
username: req.body.username,
githubID: req.body.githubID,
profileUrl: req.body.profileUrl,
avatar: req.body.avatar,
books: {
bookTitle: req.body.bookTitle,
author: req.body.author,
genre: req.body.genre
}
});
newUser.save()
.then(data => {
res.json(data)
})
.catch(err => {
res.send("Error posting to DB")
});
});
module.exports = router;
Here is my Express server:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const authRoutes = require('./routes/api/auth');
const passportSetup = require('./config/passport-setup');
const cookieSession = require('cookie-session');
const keys = require('./config/keys');
const passport = require('passport');
const profileRoutes = require('./routes/api/profile-routes');
const bookRoutes = require('./routes/api/book-routes');
// Hooks up routes/api/items file
const items = require('./routes/api/items');
const app = express();
// Boderparser Middleware
app.use(bodyParser.json());
// sets up session cookies
app.use(cookieSession({
// Max age set to 1 day
maxAge: 24 * 60 * 60 * 1000,
// Uses cookieKey from keys file to encrypt
keys: [keys.session.cookieKey]
}));
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to mongodb
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Use Routes, sets up routes/api/items to be used
app.use('/api/items', items);
app.use('/book', bookRoutes);
// Use auth.js's routes
app.use('/auth', authRoutes);
// Use profile-routes routes for profile page
app.use('/profile', profileRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`))
I'm unable to make a POST request and not sure why. The Express route handles some OAuth stuff and displays the logged in user's profile. On that same page I have the form which allows the user to add data and submit it. Is the logic from authCheck interfering with POSTing the form data? The router.post in my Express route does not successfully console.log anything.
I've seen people use Axios in the React form component itself to do a POST request. Is it better to do form POST requests with Axios or should I be handling it in the Express route?
You should use the axios for making the api call.
In your handleSubmit function you are using "event.preventDefault()" which will prevent the default behavior of the form.
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