evry node app
│
├── پوشه config
│ ├── فایل default.json
│ ├── فایل development.json
│ └── فایل development.json
│
├── پوشه src
│ ├── پوشه models
│ │ └── فایل user.js
│ └── پوشه routs
│ ├── پوشه auth
│ │ ├── فایل controller.js
│ │ ├── فایل index.js
│ │ └── فایل validator.js
│ ├── فایل controller.js
│ └── فایل index.js
│
├── فایل index.js
├── فایل package-lock.json
└── فایل package.json
دوستان در بالا پوشه بندی پروژه من را داری می بینی. و حالا موارد درون هر فایل را می گذارم.
فایل index.js:
const express = require('express');
const app = express();
app.use(express.json());
const mongoose = require('mongoose');
const config = require('config');
const router = require('./src/routs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
mongoose
.connect(config.get('db.address'))
.then(() => console.log('connected to mongodb'))
.catch((err) => console.log('could not connect to mongodb',err));
app.use('/api', router);
const port = process.env.PORT || 5000;
app.listen(5000, ()=> console.log(`listening on port ${port}`));
فایل package.json:
{
"name": "evry-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"auto-bind": "^5.0.1",
"bcrypt": "^5.1.1",
"config": "^3.3.9",
"express": "^4.18.2",
"express-validator": "^7.0.1",
"lodash": "^4.17.21",
"mongoose": "^7.4.4",
"mongoose-timestamp": "^0.6.0"
}
}
فایل config\default.json:
{
"name": "evry node app",
"db": {
"address": "mongodb://127.0.0.1:27017/test"
}
}
فایل config\development.json:
{
"name": "evry node app - dev"
}
فایل config\production.json:
{
"name": "evry node app - production"
}
فایل src\models\user.js:
const mongoose = require('mongoose');
const timestamp = require('mongoose-timestamp');
const userSchema = new mongoose.Schema({
email: {type: String, required: true, unique:true},
name: {type: String, required: true},
password: {type: String, required: true},
admin: {type: Boolean, default: false},
})
userSchema.plugin(timestamp);
const User = mongoose.model("User", userSchema);
module.exports = User;
فایل src\routs\controller.js:
const {validationResult} = require('express-validator')
const User = require('./../models/user');
module.exports = class {
constructor(){
this.User = User;
}
validatonBody(req,res){
const result = validationResult(req);
if(!result.isEmpty()){
const errors = result.array();
const massege = [];
errors.forEach(err => massege.push(err.msg));
res.status(400).json({
massege: 'validaton error',
data: massege
})
return false;
}
return true;
}
validate(req,res,next){
if(!this.validatonBody(req,res)){
return;
}
next();
}
response({res , massege , code=200 , data={}}){
res.status(code).json({
massege,
data
})
}
}
فایل src\routs\index.js:
const express = require('express');
const router = express.Router();
const authRouter = require('./auth');
router.use('/auth' , authRouter);
module.exports = router;
فایل src\routs\auth\controller.js:
const controller = require('./../controller')
const _ = require('lodash');
const bcrypt = require('bcrypt');
module.exports = new (class extends controller {
async register(req,res){
let user = await this.User.findOne({email: req.body.email});
if(user){
return this.response({
res, code: 400, massege: 'this user is registered'
});
}
user = new this.User(_.pick(req.body, ["name", "email", "password"]));
const solt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, solt);
await user.save();
this.response({
res, massege: "the user registered",
data: _.pick(user, ["_id", "name", "email"])
})
}
async login(req,res){
res.send('login');
this.User;
}
})();
فایل src\routs\auth\index.js:
const express = require('express');
const router = express.Router();
const controller = require('./controller');
const validator = require('./validator')
router.post(
'/register',
validator.registerValidator(),
controller.validate,
controller.register.bind(this)
)
router.post(
'/login',
validator.loginValidator(),
controller.validate,
controller.login.bind(this)
)
module.exports=router;
فایل src\routs\auth\validator.js:
const expressValidator = require('express-validator');
const check = expressValidator.check;
module.exports = new class {
registerValidator(){
return[
check('email')
.isEmail()
.withMessage('email id invalid')
.not()
.isEmpty()
.withMessage('email cant be empety'),
check('name')
.not()
.isEmpty()
.withMessage('name cant be empety'),
check('password')
.not()
.isEmpty()
.withMessage('password cant be empety'),
]
}
loginValidator(){
return[
check('email')
.isEmail()
.withMessage('email id invalid')
.not()
.isEmpty()
.withMessage('email cant be empety'),
check('password')
.not()
.isEmpty()
.withMessage('password cant be empety'),
]
}
}
حالا تو تمام محتوا پروژه من را داری. حالا بگو چرا زمانی که آن را اجرا می کنم به درستی اجرا می شود ولی زمانی که به این آدرس "http://localhost:5000/api/auth/register" درخواست POST می فرستم و محتوا body را به صورت زیر وارد میکنم:
{
"email": "rouzbeh@gmail.com",
"name": "rouzbeh",
"password": "1234"
}
ارور زیر را می دهد
TypeError: Cannot read properties of undefined (reading 'validatonBody')
at validate (C:\\Users\\rayanastore\\Desktop\\evry node app\\src\\routs\\controller.js:24:14)
at Layer.handle \[as handlerequest\] (C:\\Users\\rayanastore\\Desktop\\evry node app\\nodemodules\\express\\lib\\router\\layer.js:95:5)
at next (C:\\Users\\rayanastore\\Desktop\\evry node app\\nodemodules\\express\\lib\\router\\route.js:144:13)
at middleware (C:\\Users\\rayanastore\\Desktop\\evry node app\\nodemodules\\express-validator\\src\\middlewares\\check.js:16:13)
at process.processTicksAndRejections (node:internal/process/taskqueues:95:5)
به روزبه فرتاج کمک کنید تا مشکل خودش را حل کند؛ اینطور میتوانیم با هم پیشرفت کنیم.
آیا مایل به ارسال نوتیفیکیشن و اخبار از طرف راکت هستید ؟