For user authentication in node using bcrypt I have the following code but i get an error when i try to post using postman api the error is "message": "Illegal arguments: string, undefined"
The data sent through the postman is
{
"password":"1234",
"email":"[email protected]"
}
I cannot find whats wrong with the code can you please help me through this.
This is the code for server.js
import express from 'express';
import userdata from './userdata.js';
import mongoose from 'mongoose';
import userrouter from './routers/userrouter.js';
import productRouter from './routers/productrouter.js';
const app=express();
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost:27017/purpleshades',{
useUnifiedTopology: true,
useNewUrlParser: true
})
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/users/api/:id',(req,res)=>{
const k=parseInt(req.params.id)
const user1=userdata.users.find((x)=>x.uID===k)
const cartinfo=user1.ucart
const cartproductlist=[]
for (let i = 0; i < cartinfo.length; i ) {
const pid = cartinfo[i];
const productreal = data.products.find((x) => x.id === pid );
cartproductlist.push(productreal)
}
res.send(cartproductlist)
})
app.use('/api/users',userrouter)
app.use('/api/products',productRouter)
app.use((err,req,res,next)=>{
res.status(500).send({message:err.message})
})
const port=process.env.PORT || 5000
app.listen(5000,()=>{
console.log(`serve at http://localhost:${port}`);
})
code for userrouter.js
import express from "express";
import userdata from "../userdata.js";
import User from "../models/usermodel.js";
import expressAsyncHandler from "express-async-handler";
import bcrypt from 'bcryptjs'
const userrouter=express.Router()
userrouter.get('/seed',expressAsyncHandler( async(req,res)=>{
const createdusers=await User.insertMany(userdata.users)
res.send({createdusers})
}))
userrouter.post('/signin',expressAsyncHandler(async(req,res)=>{
const user=User.findOne({email: req.body.email})
if(user){
if(bcrypt.compareSync(req.body.password,user.password)){
res.send({
_id:user._id,
name:user.name,
isAdmin:user.isAdmin,
})
return
}
}
res.status(401).send({message:'invalid Email or Password'})
}))
export default userrouter
code for usermodel.js
import mongoose from "mongoose";
const userschema=new mongoose.Schema(
{
name:{type:String,required:true},
email:{type:String,required:true,unique:true},
password:{type:String,required:true},
isadmin:{type: Boolean,required:true ,default:false}
},
{
timestamps:true
}
)
const User=mongoose.model('User',userschema)
export default User
CodePudding user response:
The findOne function is asynchronous, so this line assigns a promise to the variable user:
const user=User.findOne({email: req.body.email})
Since a promise is truish, this proceeds to call compareSync, but the promise does not have a password property:
if(user){
if(bcrypt.compareSync(req.body.password,user.password)){
Await the result of the findOne to get the document instead of a promise.
