Login and registration using Nodejs + express, user data undefined - javascript

I have a simple registration page which should store the users input (name,email,password) in a database. I am using express and node. The thing i wanted to try is to have all the database operations (insert,select etc) for registration in one file and send the response to the server from another file.
dbQuery.js
var express=require("express");
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register=function(callback){
app.get('/register',function(req,res){
var today = new Date();
var users={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
return connection.query('INSERT INTO users SET ?',users, callback)
}
}
app.js
var express=require("express");
var connection = require('./dbQuery');
var app = express();
app.post('/register',function(req,res){
connection.register(function(error, results, fields){
if (error) {
res.json({
status:false,
message:'there are some error with query for registration'
})
}else{
console.log('is it coming here in else')
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
})
})
index.html
<html>
<body>
<form action="/register" method="POST">
First Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
When i execute app.js the server just keep loading without giving anything
I expected the output should be displaying the json response on server i.e 'user successfully registered' ,but it keeps on loading.

Try changing dbQuery.js to this:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "user_name",
password: "password",
database: "database"
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register = function(callback) {
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, callback);
};

You are doing wrong, here if am posting simple steps for an API by express
Your app.js file should be
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const i18n = require("i18n");
var indexRouter = require('./routes/index');
// this is the api file created under the routes folder
var apiRouter = require('./routes/api');
require('./database')
var app = express();
app.use(i18n.init);
i18n.configure({
locales: ['en', 'de'],
cookie: 'LocalLang',
defaultLocale: 'en',
extension: ".json",
directory: __dirname + '/locales',
register: global,
logDebugFn: function (msg) {
console.log('debug', msg);
},
logWarnFn: function (msg) {
console.log('warn', msg);
},
logErrorFn: function (msg) {
console.log('error', msg);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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('/', indexRouter);
app.use('/api', apiRouter);
// 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('pages/error');
});
module.exports = app;
In you api.js file which is required in app.js file
var express = require('express');
var router = express.Router();
//Import your query.js file
const query = require('path for the file ./query')
router.post('/register',query.register)
module.exports = router;
query.js file should be like
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
exports.register = (req, res)=>{
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, (error,result)=>{
if(err)
return res.send({status:false, message:"Error in savind data in db"})
return res.send({status:true, message:"Resgistered sucessfully"})
});
}

Related

Nodejs unable to post

I am very new to programming and am following a tutorial to learn.
I am stuck and am unable to post new entries using the code and am unable to find what am I missing here.
Any help will be appreciated.
When I am trying to post using postman, I am getting a Validation error, and when I am trying to get values I am getting [].
Edit: Error Msg: "msg":" Error: ValidationError: first_name: Path first_name is required., last_name: Path last_name is required., email: Path email is required."}
// importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongoDB
mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
mongoose.connection.on('connected', () => {
console.log('Connected to database mongoDB # 27017');
});
//on error
mongoose.connection.on('error', (err) => {
if (err) {
console.log('Error in DB connection' + err);
}
});
//port no
const port = 3000;
//adding middleware
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/', (req, res) => {
res.send('cutard');
});
app.listen(port, () => {
console.log('Server started at port:' + port);
});
const express = require('express');
const router = express.Router();
const Contact = require('../models/contacts');
//retriving contact
router.get('/contacts', (req, res, next) => {
Contact.find(function (err, contacts) {
res.json(contacts);
})
});
//add contact
router.post('/contacts', (req, res, next) => {
console.log(req.body)
let newContact = new Contact({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email
});
newContact.save((err, Contact)=>{
if (err) {
res.json({ msg: ' Error: '+err});
}
else {
res.json({ msg: 'Contact added successfully' });;
}
});
});
//delete contact
router.delete('/contact/:id', (req, res, next) => {
Contact.remove({ _id: req.params.id }, function (err, result){
if (err) {
res.json(err);
}
else {
res.json(result);
}
});
});
module.exports = router;
const mongoose = require('mongoose');
const ContactSchema = mongoose.Schema({
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
});
const Contact = module.exports = mongoose.model('Contact', ContactSchema);
In your req.body there are obviously no values.
Can you confirm that your body you send in postman looks like this?
{
"first_name": "xxx",
"last_name": "yyy",
"email": "zzz"
}
Also its very important to have Content-Type header set to application/json. Postman will add it automatically, if you choose JSON as format:
The problem is with the installation of body parser.
npm link body-parser

Redirect after Post method , expressjs

I'm learing ExpressJS, and so far I did the user registration part but when I want to redirect to the home page after finishing the registration, it's not
showing the json after clicking on Submit button. May I know how I could do it.
Database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
The ORM
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
The route.js
Here I insert the data obtained during registration (register index html) into a database. It's working well but I want to redirect to home page.
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", async (req, res) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password,10)
values = { username: req.body.name,
password:hashedPassword }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
values = { username: values.username,
password: values.password }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
**return res.send({
username: values.username,
password: values.password
});**
});
});
}
catch {
}
});
module.exports = router
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
To do this you need to use express's redirect method.
Example:
var express = require('express');
var app = express();
const urlBase = 'localhost:3000/'
app.post('/', function(req, res) {
const redirectUrl = "index.html"
res.redirect(urlBase + redirectUrl);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Docs: Express 4.x Docs

Could not get any response nodejs rest api

I am working on a rest api based on this tutorial from Joshmorony, I keep running on error "Could not get any response" while testing on Postman. I have tied consuming the end points on ionic3 project but still running on the same problem. What am I doing wrong that might be leading to this error? I would appreciate your support.
Here is my code.
In the controller folder controllers/authentication.js
const jwt = require('jsonwebtoken');
const bluebird = require('bluebird');
const nodemailer = require('nodemailer');
const User = require('../models/user');
const authConfig = require('../config/auth');
const crypto = bluebird.promisifyAll(require('crypto'));
/**
* Generating JWT tokens
*
*/
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role
};
}
/**
* Local login authentication
*
*/
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
/**
* Local registration
*
*/
exports.register = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
/**
* Roles Creation
*
*/
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
In the model folder model/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
var UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
unique: true,
required: true
},
password: {
type: String,
required: true
},
role: {
type: String,
enum: ['reader', 'creator', 'editor'],
default: 'reader'
},
passwordResetToken: String,
passwordResetExpires: Date,
profile: {
name: String,
gender: String,
location: String,
picture: String
}
}, {
timestamps: true
});
UserSchema.pre('save', function(next){
var user = this;
var SALT_FACTOR = 5;
if(!user.isModified('password')){
return next();
}
bcrypt.genSalt(SALT_FACTOR, function(err, salt){
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, null, function(err, hash){
if(err){
return next(err);
}
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(passwordAttempt, cb){
bcrypt.compare(passwordAttempt, this.password, function(err, isMatch){
if(err){
return cb(err);
} else {
cb(null, isMatch);
}
});
}
module.exports = mongoose.model('User', UserSchema);
Routes routes.js
const AuthenticationController = require('./controllers/authentication'),
TodoController = require('./controllers/todo'),
express = require('express'),
passportService = require('./config/passport'),
passport = require('passport');
const requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
todoRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.post('/forgot', AuthenticationController.postForgot);
authRoutes.post('/reset/:token', AuthenticationController.postReset);
authRoutes.post('/account/profile', requireAuth, AuthenticationController.postUpdateProfile);
authRoutes.post('/account/password', requireAuth, AuthenticationController.postUpdatePassword);
authRoutes.get('/protected', requireAuth, function(req, res){
res.send({ content: 'Success'});
});
// Set up routes
app.use('/api', apiRoutes);
}
and lastly app.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const errorHandler = require('errorhandler');
const chalk = require('chalk');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
const databaseConfig = require('./app/config/database');
const router = require('./app/routes');
/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
dotenv.load({ path: '.env' });
/**
* Connect to MongoDB.
*/
mongoose.Promise = global.Promise;
mongoose.createConnection(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', (err) => {
console.error(err);
console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
process.exit();
});
/**
* Express configuration.
*/
app.set('host', process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0');
app.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080);
/**
* Error Handler.
*/
app.use(errorHandler());
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
console.log(' Press CTRL-C to stop\n');
});
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
app.use(cors());
router(app);
I managed to get the error, when I was ruling the app in the terminal I got this error "DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/connections.html#use-mongo-client", when I try to modify mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); to mongoose.createConnection(process.env.MONGODB_URI || process.env.MONGOLAB_URI); thats when I get that error of "Could not get any response". Just opted to go with the old connect(). Hope this will help someone experiencing the same issue.

Mongodb -User Validation Failed

I am learning mongodb, but I am running to this wall, and I don't know how to fix it. Please help! It worked before but this time when I make post request I get this error message in Postman "User validation"
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});
UserSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password) {
var user = this;
return bcrypt.compareSync(password, user.password);
};
module.exports = mongoose.model('User', UserSchema);
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require('morgan');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var User = require('./app/models/user');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(function(req,res,next){
res.setHeader('Acess-control-allow-Origin', '*');
res.setHeader('Acess-control-Allow-Methods', 'GET, POST');
res.setHeader('Acess-Control-Allow-Headers', 'X-Requested-With, content-type,\Authorization');
next();
});
app.use(morgan('dev'));
mongoose.connect('mongodb://localhost:27017/myDatabase');
app.get('/', function(req, res){
res.send('Welcome to thome page');
});
var apiRouter = express.Router();
apiRouter.use(function(req, res, next){
console.log('Somebody just came to our app');
next();
});
apiRouter.get('/', function(req, res){
res.json({message: 'Hooray! Welcome to our api1'});
});
app.use('/api', apiRouter);
apiRouter.route('/users')
.post(function(req,res){
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err){
if(err){
if(err.code == 1000)
return res.json({success: false, message: "A user with that username already exists"});
else
return res.send(err);
}
res.json({message: "User created"});
});
});
app.listen(port);
console.log("Magic happens on port " + port);
I had this problem with postman too.
then i decided to use raw data instead of x-www-form-urlencoded with Json(application/json) header.
In your case you can use it like this :
{"name" : "Holly",
"username" : "Hollylawly",
"password" : "supersecret"}
the image for postman req
I fixed by reinstalling postman.
Thank you guys for taking your time to answer the question.
Thanks.

cannot post form in node.js express

I am very much beginner with node.js.
There is a sample form with that I am trying to insert values in database-
Here is my test page-
<form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencoded">
<input type="text" id="username_input" name="username">
<input type="text" id="password_input" name="password">
<input type="submit" name="Submit" value="Insert" class="btn">
</form>
Trying to post it-
I created test.js file and writing post method in it-
exports.list = function (req, res) {
req.getConnection(function (err, connection) {
console.log(con)
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
});
}
But this didn't work.
I tried writing post method in main server.js file also-
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
but this didn't work also.
I am following current settings in server.js file-
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index_form = require('./routes/index_form')
, user = require('./routes/user')
, test = require('./routes/test')
, mysql = require('mysql')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass#123'
});
var app =express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test', test.test);
app.get('/users', user.list);
app.get('/index_form', index_form.index_form)
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
Kindly guide me through this all , How do I make my form post with node.js?
Did you try putting app.post("/create", test.test); into your current server.js after your GET routes yet? Because what I saw here your current server.js does not have any POST request.

Categories

Resources