I am trying to create a simple registration form which i will then proceed to other CRUD operations new to node js
I have created the mysql database and done the modelling and connection with Sequelize also i have created my view with pug and i did console.log for the entries from my form and everything is fine till it gets to database insert
var express = require('express');
var router = express.Router();
var Sequelize = require("sequelize");
var db = require('../src/database/connection');
var User = require('../src/model/User');
router.get('/', function(req, res, next){
res.render('signup');
});
router.post('/register', function(req, res, next){
let { username, useremail, pass, re_pass } = req.body;
let errors = [];
//checking feilds
if( !username || !useremail || !pass || !re_pass)
{
errors.push({msg: 'Please no field should be left empty'});
}
//checking Password
if(pass !== re_pass)
{
errors.push({msg: 'Passwords Dont Match'});
}
//check Password Length
if(pass.length < 7)
{
errors.push({msg: 'Passwords should be more than 7 characters '})
}
//reload page with contents if error encountered
if(errors.length > 0)
{
res.render('signup', {
errors,
username,
useremail,
pass,
re_pass
});
} else{
console.log(req.body);
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));
}
});
module.exports = router;
This is the error i am getting. PLEASE HELP
{ SequelizeValidationError: notNull Violation: User.email cannot be null,
notNull Violation: User.password cannot be null
at Promise.all.then (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\sequelize\lib\instance-validator.js:74:15)
at tryCatcher (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at Promise._fulfill (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:638:18)
at PromiseArray._resolve (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:126:19)
at PromiseArray._promiseFulfilled (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:144:14)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:574:26)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
name: 'SequelizeValidationError',
errors:
[ ValidationErrorItem {
message: 'User.email cannot be null',
type: 'notNull Violation',
path: 'email',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] },
ValidationErrorItem {
message: 'User.password cannot be null',
type: 'notNull Violation',
path: 'password',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] } ] }
Seems like req.body is always empty
use body parser to put request body to req.body
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Thanks to everyone that tried helping me solve this problem so my mistake was that i didnt point to the database rows in the create method so what i did was
User.create({
username: req.body.username,
email: req.body.useremail,
password: req.body.pass,
}).then(user => res.redirect('signup/register')).catch(err => console.log(err));
not
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));
Related
I'm new in NodeJS I got this error ( this.$__.validationError = new ValidationError(this);)
I try to use try{..}catch(e){..} but it still the same problem inside post user but always the same
I'm confused what I should do
the error
C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125
this.$__.validationError = new ValidationError(this);
^
ValidationError: User validation failed: password: Path `password` is required.
at model.Document.invalidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125:32)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2913:17
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1349:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: {
password: ValidatorError: Path `password` is required.
at validate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1346:13) at SchemaString.SchemaType.doValidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2905:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: {
validator: [Function (anonymous)],
message: 'Path `password` is required.',
type: 'required',
path: 'password',
value: undefined
},
kind: 'required',
path: 'password',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
user schema
const mongoose = require('mongoose')
const joi = require('joi')
const User = mongoose.model('User', new mongoose.Schema({
fullname:{
type:String,
required:true,
minlength:3,
maxlength:44
},
email:{
type:String,
required:true,
unique:true,
minlength:3,
maxlength:255
},
password:{
type:String,
required:true,
minlength:3,
maxlength:1025
}
}))
const validateUser = (body , res)=>{
const schema = joi.object({
fullname:joi.string().min(3).max(44).required(),
email:joi.string().min(3).max(255).required().email(),
password:joi.string().min(8).max(255).required()
})
const {error} = schema.validate(body)
if(error){
return res.status(404).send(error.message)
}
}
module.exports = {User,validateUser}
user routes
const express = require('express')
const router = express.Router()
const {User , validateUser} = require('../model/user')
//add new user
router.post('/' , async(req,res)=>{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
})
module.exports = router
index.js
const mongoose = require('mongoose')
const app = express()
//for devlopment envirement
if(app.get('env') === 'development'){
app.use(morgan('tiny'))
}
mongoose.set('strictQuery', false);
mongoose.connect("mongodb://localhost:27017/expDB", { useNewUrlParser: true })
.then(()=> console.log("connected to database"))
.catch((error)=>console.error("there is an error" + error))
//using the middlewares
app.use(helmet())
app.use(express.json())
app.use('/employees', employees)
app.use('/user' , user)
//running the server
const PORT = process.env.PORT || 3000
app.listen(PORT , ()=>{
console.log(`app ronning on PORT ${PORT}...`)
})
when I added try catch in post user I got this error
node:internal/errors:477
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:278:15)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:162:21)
at C:\Users\toshiba\Desktop\express project\routes\user.js:18:19
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
post req
//add new user
router.post('/' , async(req,res)=>{
try{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
}catch(err){
res.status(404).send(err)
}
})
Sorry this is my first attempt at doing backend, it's probably a silly question. I have an index.js like so:
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const userRoute = require('./routes/user')
const authRoute = require('./routes/auth')
const PORT = process.env.PORT || 5000
dotenv.config()
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('db connection succesful'))
.catch((err) => {
console.log(err)
})
app.use(express.json())
app.use('/api/auth', authRoute)
app.use('/api/users', userRoute)
app.listen(PORT, () =>{
console.log(`backend server is running! on ${PORT}`)
})
My auth.js looks like:
const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
//REGISTER
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Wrong User Name");
password = user.password
password !== req.body.password && res.status(401).json("Wrong credentials!");
res.status(200).json(user)
} catch(err) {
res.status(500).json(err);
}
});
module.exports = router;
And not sure if this is relevant but my User.js like so:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
I am sending a JSON object to my register route:
{
"username": "test",
"email": "100#gmail.com",
"password": 123456
}
Which works. I get the following response in the body when posting to http://localhost:5000/api/auth/register:
{
"username": "test",
"email": "100#gmail.com",
"password": "123456",
"isAdmin": false,
"_id": "62fd49a6baa5717b67a885df",
"createdAt": "2022-08-17T20:03:50.776Z",
"updatedAt": "2022-08-17T20:03:50.776Z",
"__v": 0
}
But then when I try post an object to my login (http://localhost:5000/api/auth/login):
{
"username": "test",
"password": "123456"
}
I get the following error:
~/code/IaaS/app$ npm start
> app#0.1.0 start
> nodemon index.js
[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
backend server is running! on 5000
db connection succesful
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:278:15)
at /home/a7dc/code/IaaS/app/routes/auth.js:37:25
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
What am I doing wrong?
Thank you to Ariel for their answer. I have updated the code to the following:
//LOGIN
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Wrong User Name");
password = user.password
password !== req.body.password && res.status(401).json("Wrong credentials!");
if (password !== req.body.password) {
return res.status(401).json("Wrong credentials!");
} else {
return res.status(200).json(user)
}
} catch(err) {
console.log('error')
return res.status(500).json(err);
}
});
module.exports = router;
Which gives the error:
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
backend server is running! on 5000
db connection succesful
error
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:278:15)
at /home/a7dc/code/IaaS/app/routes/auth.js:42:32
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
The problem is that you are sending a response twice (the program is not stopping when you send a response). Here you are sending a response with status 401 and then a response with status 200.
password !== req.body.password && res.status(401).json("Wrong credentials!");
res.status(200).json(user)
Probably, you want to send 401 if the password is different and 200 otherwise
if (password !== req.body.password) {
res.status(401).json("Wrong credentials!");
} else {
res.status(200).json(user)
}
Or maybe, just "return" when the response is sent. Example:
return res.status(XXX).json({ something: "something})
"Cannot set headers after they are sent to the client" means that one response is already sent so you can't set the headers again.
So I know there are tons of similar questions out there, and I've read most of them in the past few days. However I didn't find any solution to my problem. The app is about users can post memories(cards) etc... Point is, when I create a new card with POST request, there is no problem, but when I want to sign up a user then all hell breaks loose and throws this error:
(node:2732) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property 'firstName' of 'req.body' as it is undefined.
at signup (file:///E:/projects/personal/memories-app/backend/controllers/user.controller.js:39:13)
at Layer.handle [as handle_request] (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\layer.js:95:5)
at next (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\route.js:137:13)
I don't know that could be the problem, because other functions work so dunno really.
Here are the codes
server.js
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import postRoutes from './routes/posts.routes.js';
import userRoutes from './routes/users.routes.js';
const app = express();
dotenv.config();
app.use(express.json({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
app.get('/', (req, res) => {
res.send('Hello to Memories API');
});
const PORT = process.env.PORT || 5000;
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () => console.log(`Server running on port: ${PORT}`))
)
.catch((error) => console.log(error.message));
mongoose.set('useFindAndModify', false);
user.model.js
import mongoose from 'mongoose';
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
id: { type: String },
});
export default mongoose.model('User', userSchema);
the sign up method from user.controller.js
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import User from '../models/user.js';
export const signup = async (res, req) => {
const { firstName, lastName, email, password, confirmPassword } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: 'User already exists' });
if (password !== confirmPassword)
return res.status(400).json({ message: "Passwords don't match" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
'test',
{
expiresIn: '1h',
}
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
};
and just to see the createPost method (which works) from post.controller.js
import PostMessage from '../models/postMessage.js';
import mongoose from 'mongoose';
export const createPost = async (req, res) => {
const post = req.body;
console.log(post);
const newPost = new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
}
};
And there is no problem with the front-end because when I simply console.log the req, I can see the body, but if I were to clg the req.body, then it is undefined. I've tried it with postman also, but no luck.
I would appreciate any insight on this! Thanks in advance!
You need to swap the order of res and req in the signup function, replace:
export const signup = async (res, req) => {
by:
export const signup = async (req, res) => {
Your User model does not have a firstName, lastName, and confirmPassword types use { name, email, password, } = req.body to sign up a new user.
In your project frontend use
name email, password, confirmPassword to register a use and email, password to log users in.
this is my mean code.
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jet = require('jsonwebtoken');
const Contact = require('../models/contacts');
// retrieving Data
router.get('/contacts',(req,res,next)=>{
// res.send('Retriving the contact list');
console.log('contacts page');
Contact.find(function(err, contacts){
res.json(contacts);
})
});
// to add the content
router.post('/contact',(req, res, next)=>{
// logic to add contact
let newContact = new Contact({
first_name: req.body.first_name,
last_name: req.body.last_name,
email_id: req.body.email_id,
password: req.body.password
});
Contact.addRegistry((err, contacts)=> {
if(err) {
res.json({msg:'faild to add register'});
}
else{
res.json({msg:'registry added sucessfully'});
}
});
});
// to delete the content
router.delete('/contact/:id',(req, res, next) =>{
// logic to delete contact
Contact.remove({_id:req.params.id}, function(err, result){
if(err){
res.json(err);
}
else {
res.json(result);
}
});
})
module.exports = router;
the above file is route.js.
the below code is from contact.js
// Database code.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
// database schaema
var ContactSchema = new mongoose.Schema({
first_name: String,
last_name: String,
id: String,
location: String,
profile_picture_url: String,
email_id: String,
phone: String,
job_title: String,
company: String,
education: String,
password: String,
savedjobslist: {
title: [],
subtitle: []
},
appliedjobslist: {
title: [],
subtitle: []
},
failedjobslist: {
title: [],
subtitle: []
}
});
const Contact = module.exports = mongoose.model('Contact', ContactSchema);
module.exports.getUserById = function(id,callback) {
Contact.findById(id,callback);
}
module.exports.getUserById = function(username,callback) {
const query = {username: username}
Contact.findOne(query,callback);
}
module.exports.addRegistry = function(newContact,callback) {
bcrypt.genSalt(10, (err,salt) => {
bcrypt.hash(newContact,salt, (err,hash) => {
if (err) {
console.log(err);
}
newContact.password = hash;
newContact.save(callback);
});
});
}
I'm trying to post the data from postman it is shoing the error as
"there was error connecting to http://localhost:3000/api/contact"
and in the command prompt it is showing the error as
Server started at port3000 connected to mongos database at 27017
Error: Illegal arguments: function, string
at _async (D:\project-1\back-end\node_modules\bcryptjs\dist\bcrypt.js:214:46 )
at Object.bcrypt.hash (D:\project-1\back-end\node_modules\bcryptjs\dist\bcry pt.js:220:13)
at bcrypt.genSalt (D:\project-1\back-end\models\contacts.js:49:16)
at Immediate._onImmediate (D:\project-1\back-end\node_modules\bcryptjs\dist\ bcrypt.js:153:21)
at runCallback (timers.js:794:20)
at tryOnImmediate (timers.js:752:5)
at processImmediate [as _immediateCallback] (timers.js:729:5) D:\project-1\back-end\models\contacts.js:54
newContact.save(callback);
^
TypeError: newContact.save is not a function
at bcrypt.hash (D:\project-1\back-end\models\contacts.js:54:23)
at runCallback (timers.js:794:20)
at tryOnImmediate (timers.js:752:5)
at processImmediate [as _immediateCallback] (timers.js:729:5) [nodemon] app crashed - waiting for file changes before starting...
newContact.save(callback);
^
TypeError: newContact.save is not a function.
i don't know why this error is coming.
You have an issue here:
bcrypt for generating is throwing an error because of wrong parameters. You can't pass object (newContact) to bcrypt.
Try to generate a hash using the following code:
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
You can use pre save function of mangoose to generate hashedPassword while storing this. Personally, I don't prefer as this adds new check everytime you save the object
find() takes query as an argument to search all pass {}
Contact.find({},function(err, contacts){
res.json(contacts);
})
Contact.addRegistry waits newContact as first parameter, but you do not pass it on your route.js
I think you want to do something like this
ContactSchema.pre('save', function(next) {
const user = this;
// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
// hash your password
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// store hash on the password field
user.password = hash;
next();
});
});
});
I'm using Express and Sequelize to make a basic user authentication based upon this tutorial
When I want to sign a token to a user I get an error telling me I'm trying to JSON.stringify() a circular reference which cannot be done. Therefor an error is thrown and I can't assign the token to the user.
OR I am doing something wrong when finding my user in the database which makes a circular reference OR I just need to find a solution to break the circular reference I suppose. Anyone who could explain me which of the two it is?
The full error is:
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at toString (/Users/Desktop/express-jwt/node_modules/jws/lib/tostring.js:9:15)
at jwsSecuredInput (/Users/Desktop/express-jwt/node_modules/jws/lib/sign-stream.js:12:34)
at Object.jwsSign [as sign] (/Users/Desktop/express-jwt/node_modules/jws/lib/sign-stream.js:22:22)
at Object.module.exports [as sign] (/Users/Desktop/express-jwt/node_modules/jsonwebtoken/sign.js:144:16)
at Model.User.findOne.then.user (/Users/Desktop/express-jwt/server/index.js:69:27)
at Model.tryCatcher (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/promise.js:691:18)
at Async._drainQueue (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues (/Users/Desktop/express-jwt/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
My index for the server is:
const express = require(`express`);
const app = express();
const bodyParser = require(`body-parser`);
const morgan = require('morgan');
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
const config = require('./config'); // get our config file
const db = require(`./models`);
const User = global.db.User;
const port = process.env.PORT || 8080;
db.sequelize.sync().then(() => {
console.log(`Express server listening on port ${port}`);
});
app.set('superSecret', config.secret);
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
app.get('/setup', (req, res) => {
db.sequelize.sync().then(() => {
return User.create({
username: 'Kevin frafster',
password: 'password',
admin: true
})
.then(addedUser => {
console.log(addedUser.get({
plain: true
}));
})
.catch(err => {
res.json(err);
});
});
});
// API ROUTES -------------------
// get an instance of the router for api routes
const apiRoutes = express.Router();
apiRoutes.post('/authenticate', (req,res) => {
User.findOne({
where: {username: req.body.username}
}).then(user => {
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.'});
}else{
// console.log(user);
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' })
}else{
const token = jwt.sign(user, app.get('superSecret'), {
expiresIn: 60*60*24
});
res.json({
succes: true,
message: 'Enjoy your token!',
token
});
}
}
}).catch(err => {
res.status(500).json(err);
})
});
// TODO: route to authenticate a user (POST http://localhost:8080/api/authenticate)
// TODO: route middleware to verify a token
// route to show a random message (GET http://localhost:8080/api/)
apiRoutes.get('/', (req, res) => {
res.json({ message: 'Welcome to the coolest API on earth!' });
});
// route to return all users (GET http://localhost:8080/api/users)
apiRoutes.get('/users', (req, res) => {
User.findAll({})
.then(users => {
res.json(users);
})
.catch(err => {
res.json(err);
});
});
// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);
Well, the answer was totally peanuts.
1) Make new object and assign payload to it
const payload = {username: user.username, password: user.password};
2) Use the new object to assign token to
const token = jwt.sign(payload, app.get('superSecret'), {
expiresIn: 60*60*24
});