When I search in the browser as localhost:/users/register
I am getting Cannot GET /users/register
but I have specified the request as post in router. I have imported the body-parser in the app.js
The post request is present in routes/users.js
router.post("/register",(req,res,next)=>{ console.log("Post request"); let newUser=new User({ name:req.body.name, email:req.body.email, username:req.body.username, password:req.body.password }) User.addUser(newUser,(err,user)=>{ if(err) res.json({success:false,msg:"Failed to register user"}) else res.json({success:true,msg:"User registration successful"}) }) })
Schema in models/user.js
const mongoose=require("mongoose") const bcrypt = require("bcryptjs") const config = require("../config/database") const UserSchema=mongoose.Schema({ name:{type:String}, email:{type:String,required:true}, username:{type:String,required:true}, password:{type:String,required:true} }) const User = module.exports=mongoose.model("User",UserSchema) module.exports.getUserById=function(id,callback){ User.findById(id,callback) } module.exports.getUserbyUsername=function(username,callback){ query={username:username} User.findOne(query,callback) } module.exports.addUser=function(newUser,callback){ bcrypt.genSalt(10,(err,salt)=>{ bcrypt.hash(newUser.password,salt,(err,hash)=>{ newUser.password=hash newUser.save(callback) }) }) }
Your route is written as a post request. So, when you try to search for it through the browser that request will be treated as a get request. if you want to test your post requests try it with some tools like Postman.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.