my user.js
const express=require('express')
const router=express.Router()
const gravatar=require('gravatar')
const bcrypt=require('bcryptjs')
const {check,validationResult} =require('express-validator/check')
const User=require('../../models/User')
//@route POST api/users
//@desc Register user
//@access public
router.post('/',[
check('name','Name is required').not().isEmpty(),
check('email','please include a valid email').isEmail(),
check('password','please enter password with more than 6 characters').isLength({min:6})
],async(req,res)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors:errors.array()})
}
const {name,email,password}=req.body;
try{
//see if the user exists
let user = await User.findOne({ email: email })
//if record exists in DB
if (user) {
return res.status(400).json({ errors: [{ msg: "user already exists" }] });
}
//get users gravatar
const avatar=gravatar.url(email,{
s:'200', //size
r:'pg', //rating of image
d:'mm' //gives a default image
})
user=new User({
name,
email,
avatar,
password
})
//encrpyt password
const salt=await bcrypt.genSalt(10) // 10-no of rounds.more the better
user.password=await bcrypt.hash(password,salt); //coverts to hash pass
await user.save();
//return jsonwebtoken
res.send('User registered')
}catch(e){
console.log(e.message)
res.status(500).send('server error')
}
res.send('User route')
})
module.exports=router;
the app is working fine but in the terminal i get
(node:1022) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:464:11) at ServerResponse.header (/Users/udayshetty/Desktop/MERN app/node_modules/express/lib/response.js:771:10) at ServerResponse.send (/Users/udayshetty/Desktop/MERN app/node_modules/express/lib/response.js:170:12) at /Users/udayshetty/Desktop/MERN app/routes/api/users.js:60:9 at processTicksAndRejections (internal/process/task_queues.js:85:5) (node:1022) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:1022) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.