server.js
const express = require("express");
const expressValidator = require("express-validator");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const port = 5846;
/**
*
*/
const userApi = require("./router/api/user");
const db = require("./config/key").mongoURI;
mongoose.connect(db,{ useNewUrlParser: true }).then( () => console.log("")).catch((err) => console.log(err));
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json());
app.use(expressValidator());
/**
*
*/
app.use("/api/user",userApi);
/**
* app
*/
app.listen(port,() => {
//
console.log("")
});
router / api / user.js is the interface file in server.js
const express = require("express");
const {checkBody} = require("express-validator");
const bcrypt = require("bcryptjs");
const router = express.Router();
const UserModel = require("../../models/User");
/**
*
* POST api/user/register
*/
router.post("/register",(req,res) => {
req.checkBody("userName", "Enter a user name.").notEmpty().trim();
req.checkBody("userEmail","Enter a valid email address.").notEmpty();
req.checkBody("userPassword","Enter a user password.").notEmpty();
UserModel.findOne({userName:req.body.userName})
.then((user) => {
if(user){
return res.status(400).json({userName:""})
}else{
const newUser = new UserModel({
userName: req.body.userName,
userEmail:req.body.userEmail,
userPassword: req.body.userPassword,
userDate:req.body.userDate
});
//
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.userPassword, salt, (err, hash) => {
if(err){
console.log(err);
res.send({
message :"Post request error!"
});
}
newUser.userPassword = hash;
//
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
}
use postman to test data and return error message:
:
I don"t know what"s wrong with this reason. Ask for advice.
does it have to be verified before the submission can be successful?