当我在浏览器中以localhost:/ users / register
进行搜索时我收到Cannot GET /users/register
,但已在路由器中将请求指定为post。我已经将body-parser导入了app.js
发布请求存在于route / 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"})
})
})
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)
})
})
}