I am developing an API using NodeJS with the functionality of user registration and login. When a user register, I get
"Error: WHERE parameter "email" has invalid "undefined" value" this
error."
I have checked similar question and answer here and tried every one of them, but none has worked for me.
app.js file
```
//use path module
const path = require('path');
//use express module
const express = require('express');
//use ejs view engine
const ejs = require('ejs');
//use bodyParser middleware
const bodyParser = require('body-parser');
//use mysql database
const mysql = require('mysql');
const app = express();
//Setting port number
const port = process.env.PORT || 619;
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user:'root',
password: '',
database: 'home_automation_db'
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.locals.stuff = {
url : req.originalUrl
}
next();
});
//connecting to database
mysqlConnection.connect((err) =>{
if(!err)
console.log('DB connection successful');
else
console.log('connection failed \n Error: '+JSON.stringify(err, undefined, 2));
});
var Users = require('./controllers/lightController');
app.use('/users', Users);
//server listening
app.listen(port, () => {
console.log('Server is running at port '+port);
});
lightcontroller.js
```var bodyParser= require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var generator = require('generate-password');
var nodemailer = require('nodemailer');
const bcrypt = require('bcrypt');
const cors= require('cors')
const jwt = require('jsonwebtoken');
const express =require('express')
const users = express.Router();
const User = require('../models/User');
users.use(cors());
process.env.SECRET_KEY = 'secret';
```
```
// Login controller
users.post('/register', function (req, res) {
const userData = {
user_name: req.body.username,
email: req.body.email,
password: req.body.password,
location: req.body.location,
house_number: req.body.house_number
}
User.findOne({
where: {
email: req.body.email
}
}).then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData).then(user => {
res.json({ status: user.email + "registered" })
}).catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({ error: "user already exist." })
}
}).catch(err => {
res.send('error: '+err)
})
});
```
User model
const Sequelize = require('sequelize')
const db = require("../database/db")
module.exports = db.sequelize.define(
'user_tb',
{
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
user_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
house_number: {
type: Sequelize.STRING
}
},
{
timestamps: false,
freezeTableName: true
}
)
As #messerbill said the most probable cause is the sending of data as undefined
Try adding config after post data to your post request on the client side so it sets proper content-type:
axios.post('http://localhost:9000/api/login', {
email: this.state.email,
password: this.state.password,
}, {
'content-type': 'x-www-form-urlencoded'
}).then(res => {
console.log(res);
if(res.status) {
console.log('User is logged in');
}
}).catch(err => console.log(err))
Related
When I'm uploading data about my new user I don't get any information back with the new json file where is saved my user, I only get '{}' and that's all. I'm sending here my code and what I get in Postman.
index.js
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const mongoose = require('mongoose');
const { CLIENT_RENEG_LIMIT } = require('tls');
const { application } = require('express');
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('Connected to Mongoose server'))
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use('/api/users', userRoute);
app.use('/api/auth', authRoute);
app.listen(process.env.PORT || 5200, ()=>{
console.log('Listening on port 5200');
});
auth.js
const router = require('express').Router();
const user = require('../models/user');
//REJESTRACJA
router.post('/rejestracja', async (req, res)=>{
const newUser = new user({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const saveduser = newUser.save();
res.status(201).json(saveduser);
}catch(err){
res.status(500).json(err);
}
});
module.exports = router
user.js
const mongoose = require('mongoose');
const {Boolean} = require('webidl-conversions');
const UserSchema = new mongoose.Schema({
username: { type: 'string', unique: true, required: true},
email: { type: 'string', unique: true, required: true},
password: { type: 'string', required: true, unique: true},
admin: { type: 'Boolean', default: false},},
{timestamps: true}
)
module.exports = mongoose.model('User', UserSchema);
postman screenshot
This is my first post on stackoverflow so I apologize in advance if the form of my post is weird. I'm looking to use sessions with express-session to persist a user's connection in a react application. With PostMan, the cookie is saved, the back-end recognizes the user while from my browser which performs a post request with axios I send a (res.send (req.session)))
receives the session, but after another call is not recognized by the server.
My server code:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const sha1 = require('sha1');
const cors = require('cors');
const path = require('path');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const React = require('react');
const app = express();const MONGOURI = "mongodb+srv://loulou00:loulou00#cluster0.2t92n.mongodb.net/User?retryWrites=true&w=majority";
//connect to mongoose db
mongoose.connect(MONGOURI, {useNewUrlParser: true})
.then(() => console.log('DB CONNECTED'))
.catch(error => console.log(error));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../build')));
app.use(cors({credentials: true, origin: 'http://localhost:1200', exposedHeaders: ["set-cookie"],}));
let sess = {
secret: 'keyboard cat',
cookie: {
maxAge: 60000
},
resave: true,
saveUninitialized: true
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}
app.use(session(sess))
const { Customer } = require('./models/customer');
const { response } = require('express');
//API ROUTE
app.get('/zeb', function (req, res) {
res.send(req.session)
console.log(req.session)
//res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
})
app.post('/api/token_add', (req, res) => {
if (req.body.secret == 'super secret')
{
Customer.findOne({ name: req.body.name }, (err, response) => {
if (!response)
{
const token = sha1(req.body.name)
const customer = new Customer({
name: req.body.name,
pack: req.body.pack,
token: token,
}).save((e, resp) => {
if(e) res.status(400).send(e);
res.status(200).send(resp);
console.log(resp);
})
}
else
{
res.status(400).send('This name is already use')
}
})
}
})
app.post('/api/token_connect', (req, res) => {
Customer.findOne({ token: req.body.token }, (err, response) => {
if(err) res.status(400).send(err)
if (response) {
req.session.token = req.body.token;
res.status(200).send(req.session);
console.log(req.session)
}
else{
res.send('Invalid token')
}
})
});
app.get('/api/token_getinfo', (req, res) => {
console.log(req.session)
Customer.findOne({ token: req.query.token }, (err, response) => {
if(err) res.status(400).send(err)
if (response) {
res.status(200).send(response);
}
else{
res.send('Invalid token')
}
})
})
app.get('/api/token_connectsess', (req, res) => {
console.log(req.session)
Customer.findOne({ token: req.session.token }, (err, response) => {
if(err) res.status(400).send(err)
if (response) {
res.status(200).send(req.session);
}
else{
res.send('Invalid token')
}
})
});
const port = process.env.PORT || 1200;
app.listen(port, () => {
console.log('Server runnin on ' + port)
})
My axios request:
const connect = () => {
axios.post('http://192.168.1.24:1200/api/token_connect', {token: token}
,{
"headers": {
"content-type": "application/json",
}
}).then((res) => {
if (res.data.token)
{
console.log(res.data.token);
setUser(res.data.token) ;
}
})
}
The session :
Session {
cookie: {
path: '/',
_expires: 2020-10-26T22:14:31.294Z,
originalMaxAge: 60000,
httpOnly: true
},
token: 'f7ed376ba27377ae2680fafe1a67037df80b7e36'
}
you need to pass this {withCredentials: true} as an option in your request
For Example:
axios.post(API_SERVER + '/login', { email, password }, { withCredentials: true })
This is an example site that I have created with a basic Node.js server. I am able to successfully post, create a user given the schema, and "save" to the database; however, saving does not return the user object and cannot be found in my actual database. The connection is also returned as successful.
main.js
const session = require('express-session');
const pug = require('pug');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('./schema.js');
const app = express();
var path = require('path');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
var db;
client.connect((err, client) => {
if (err) {
console.log(err);
}
else if (!err) {
db = client.db('node');
console.log('Connected to Mongodb');
client.close()
}
});
app.engine('pug', require('pug').__express)
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'styles')));
app.use(session({secret: 'testing',saveUninitialized: true,resave: true}));
//root directory get response
app.get('/', (req, res) => {
res.render('homepage', {
title : 'Homepage',
req : req
});
});
//register directory get response
app.get('/register', (req, res) => {
res.render('register', {
title : 'Register',
req: req
});
});
//profile directory get response
app.get('/profile', (req, res) => {
res.render('profile', {
title: 'Profile',
email: req.session.email,
username: req.session.username,
req: req
});
});
//login directory get response
app.get('/login', (req, res) => {
res.render('login', {
title: 'Login',
req: req
})
})
//register directory post request
app.post('/register', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.email && req.body.password){
var user = User({
email : req.body.email,
username : req.body.username,
password : req.body.password
});
console.log(user);
user.save((err) => {
user.markModified('password')
console.log("Trying to save")
console.log(user)
if(err){
console.log(err);
} else {
var sess = req.session;
sess.email = req.body.email;
console.log("Saved")
res.redirect('/profile')
}
});
}
});
//login directory post request
app.post('/login', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.password){
var sess = req.session;
sess.username = req.body.username;
res.redirect('/profile')
}
})
const server = app.listen(8000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});
schema.js
const bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
unique: false,
required: true,
trim: true
}
});
UserSchema.pre('save', function(req, err, next) {
var user = this;
bcrypt.genSalt(10, (err, salt) => {
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if(err){
return next(err);
}
user.password = hash;
console.log(hash);
next()
});
});
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
You are using mongoose to create models and make db querys but not connecting to mongoose. Instead you are connecting to MongoDb native driver.
Replace this
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
var db;
client.connect((err, client) => {
if (err) {
console.log(err);
}
else if (!err) {
db = client.db('node');
console.log('Connected to Mongodb');
client.close()
}
});
with
mongoose.connect(connectionString, {useNewUrlParser: true});
mongoose.connection.on("open", function(ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on("error", function(err) {
console.log("Could not connect to mongo server!");
console.log(err);
});
Try this var user = new User({ ... }); instead of this var user = User({ ... });. Notice the new keyword.
I'm trying to build server side back-end code for my website.
I tried app.get request in postman and it worked but when I tried
app.post request in postman it didn't work and gave me errors.
I tried all the solution that was available online and I could understand (I'm Ubuntu user).
Error Screenshot that I get in Postman
The following image will show you the error and format I used in postman
Server.js File (main server file)
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const app = express();
const mongoose = require("mongoose");
require("dotenv").config();
mongoose.Promise = global.Promise;
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// // DB config
mongoose.set("useCreateIndex", true);
// const db = require("./config/keys").mongoURI;
// Connect to MongoDB
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
// Models
const { User } = require("./models/user");
//====================================================
// USERS
//====================================================
app.post("/api/users/register", (req, res) => {
const user = new User(req.body);
user.save((err, doc) => {
if (err) return res.json({ success: false, err });
res.status(200).json({ success: true, userdata: doc });
});
});
app.get("/", (req, res) => res.send("hello world"));
const port = process.env.PORT || 3002;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
User Model file (models/user.js)
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
email: {
type: String,
requrired: true,
trim: true,
unique: 1
},
password: {
type: String,
requrired: true,
minlength: 5
},
name: {
type: String,
requrired: true,
maxlength: 100
},
lastname: {
type: String,
requrired: true,
maxlength: 100
},
cart: {
type: Array,
default: []
},
history: {
type: Array,
default: []
},
role: {
type: Number,
default: 0
},
token: {
type: String
}
});
const User = mongoose.model("User", userSchema);
module.exports = { User };
pass this has a raw data from postman and then call the post api
{
"email": "rohan#getMaxListeners.com",
"password":"pass#123",
"name":"sher",
"lastname":"lock"
}
Postman request should be like below.
{
"email": "rohit***#gmail.com",
"password": "password#123",
"name": "sher",
"lastname": "lock"
}
You are sending an invalid JSON.
Use this JSON for sending Request.
{
"email":"rohan3131313#gmail.com",
"password":"password#123",
"name":"sher",
"lastname:"lock"
}
I've been struggling with Bcrypt on my MERN project, I'm trying to run tests on Postman (registration process), but every time I try it I get this error: Error: Illegal arguments: undefined, string on this line:
if (err) throw err;
This is my server main config file:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const users = require('./routes/api/users');
const profile = require('./routes/api/profile');
const posts = require('./routes/api/posts');
const app = express();
// Body parser Middleware
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// MongoDB Config
const db = require('./config/keys').mongoURI;
// MongoDB Connection
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.get('/', (req, res) => res.send('Hello!'));
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server Runing on port ${port}`));
// Using Routes
app.use('/api/users', users);
app.use('/api/profile', profile);
app.use('/api/posts', posts);
And this is the users config file where I'm getting the error:
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
// Load user model:
const User = require('../../models/User');
router.get('/test', (req, res) => res.json({ msg: "Users Works" }));
router.post('/register', (req, res) => {
User.findOne({ email: req.body.email })
.then(user => {
if (user) {
return res.status(400).json({ email: "Email already exists" });
} else {
const avatar = gravatar.url((req.body.email, {
s: '200', // Size
r: 'pg', // Rating
d: 'mm' // Default image
}));
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err));
})
})
}
})
})
module.exports = router;
this is what I see on Postman:
I've been reviewing it and it doesn't seem to have any error, and I really don't get why is telling me "undefined string". If you see any error that I'm not noticing I will truly appreciate your feedback, Thanks in advance!
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar, <------------------------- avatar:'', or avatar:null,
password: req.body.password
});