Kirish
Node.js va Express.js zamonaviy web ilovalarning backend qismini yaratish uchun eng mashhur texnologiyalardan biri. Ushbu maqolada siz noldan boshlab to'liq ishlaydigan REST API yaratishni o'rganasiz.
1. Node.js nima?
Node.js - bu Chrome V8 JavaScript engine'ga asoslangan runtime environment bo'lib, JavaScript'ni serverda ishlatish imkonini beradi.
Node.js'ning asosiy xususiyatlari:
- Non-blocking I/O: Asinxron operatsiyalar tufayli yuqori performance
- Event-driven: Event loop mexanizmi orqali ishlaydi
- Single-threaded: Bitta thread'da ishlaydi, lekin ko'p so'rovlarni bir vaqtda boshqaradi
- NPM: 2 million+ paketlar bilan eng katta ekotizim
Node.js o'rnatish
# Windows/Mac/Linux uchun nodejs.org'dan yuklab oling
# Versiyani tekshirish
node --version
npm --version
2. Express.js bilan boshlash
Express.js - Node.js uchun minimal va moslashuvchan web framework.
Loyiha yaratish
# Yangi papka yaratish
mkdir my-api
cd my-api
# package.json yaratish
npm init -y
# Express o'rnatish
npm install express
# Development uchun nodemon
npm install --save-dev nodemon
Birinchi server
// server.js
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware - JSON ma'lumotlarni qabul qilish
app.use(express.json());
// Route - GET /
app.get('/', (req, res) => {
res.json({ message: 'API ishlayapti!' });
});
// Serverni ishga tushirish
app.listen(PORT, () => {
console.log(`Server ${PORT}-portda ishlamoqda`);
});
Serverni ishga tushirish
# Oddiy usul
node server.js
# Nodemon bilan (avtomatik restart)
npx nodemon server.js
💡 Maslahat
Development jarayonida nodemon ishlatish vaqtingizni tejaydi - har safar kod o'zgarganda server avtomatik qayta ishga tushadi.
3. REST API yaratish
CRUD (Create, Read, Update, Delete) operatsiyalarini qo'llab-quvvatlaydigan users API yaratamiz.
// server.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
// Ma'lumotlar bazasi (demo uchun array)
let users = [
{ id: 1, name: 'Ali', email: 'ali@example.com' },
{ id: 2, name: 'Vali', email: 'vali@example.com' }
];
// GET - Barcha foydalanuvchilar
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET - Bitta foydalanuvchi
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).json({ message: 'Foydalanuvchi topilmadi' });
}
res.json(user);
});
// POST - Yangi foydalanuvchi
app.post('/api/users', (req, res) => {
const { name, email } = req.body;
// Validation
if (!name || !email) {
return res.status(400).json({ message: 'Name va email majburiy' });
}
const newUser = {
id: users.length + 1,
name,
email
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT - Foydalanuvchini yangilash
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).json({ message: 'Foydalanuvchi topilmadi' });
}
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
res.json(user);
});
// DELETE - Foydalanuvchini o'chirish
app.delete('/api/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) {
return res.status(404).json({ message: 'Foydalanuvchi topilmadi' });
}
users.splice(index, 1);
res.json({ message: 'Foydalanuvchi o\'chirildi' });
});
app.listen(PORT, () => {
console.log(`Server ${PORT}-portda ishlamoqda`);
});
4. Middleware
Middleware - bu request va response o'rtasida bajariladigan funksiyalar.
Custom Logger Middleware
// Logger middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next(); // Keyingi middleware'ga o'tish
};
app.use(logger);
Authentication Middleware
const authMiddleware = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ message: 'Token yo\'q' });
}
// Token tekshirish (demo)
if (token !== 'Bearer my-secret-token') {
return res.status(403).json({ message: 'Noto\'g\'ri token' });
}
next();
};
// Himoyalangan route
app.get('/api/protected', authMiddleware, (req, res) => {
res.json({ message: 'Bu himoyalangan ma\'lumot' });
});
Error Handling Middleware
// Xatolarni ushlash (oxirgi middleware)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
message: 'Server xatosi',
error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
5. MongoDB bilan ishlash
Real loyihalarda ma'lumotlar bazasi kerak bo'ladi. MongoDB'ni ishlatamiz.
MongoDB va Mongoose o'rnatish
npm install mongoose
MongoDB'ga ulanish
// config/database.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('MongoDB\'ga ulanildi');
} catch (error) {
console.error('MongoDB xatosi:', error);
process.exit(1);
}
};
module.exports = connectDB;
User Model yaratish
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Ism majburiy'],
trim: true
},
email: {
type: String,
required: [true, 'Email majburiy'],
unique: true,
lowercase: true
},
password: {
type: String,
required: [true, 'Parol majburiy'],
minlength: 6
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
CRUD operatsiyalar MongoDB bilan
// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// Barcha foydalanuvchilar
router.get('/', async (req, res) => {
try {
const users = await User.find().select('-password');
res.json(users);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Bitta foydalanuvchi
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id).select('-password');
if (!user) {
return res.status(404).json({ message: 'Topilmadi' });
}
res.json(user);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Yangi foydalanuvchi
router.post('/', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// Yangilash
router.put('/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
).select('-password');
if (!user) {
return res.status(404).json({ message: 'Topilmadi' });
}
res.json(user);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// O'chirish
router.delete('/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).json({ message: 'Topilmadi' });
}
res.json({ message: 'O\'chirildi' });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
module.exports = router;
6. JWT Authentication
JSON Web Token bilan xavfsiz autentifikatsiya tizimi yaratamiz.
Kerakli paketlar
npm install jsonwebtoken bcryptjs
Auth Controller
// controllers/authController.js
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
// Register
exports.register = async (req, res) => {
try {
const { name, email, password } = req.body;
// Foydalanuvchi mavjudligini tekshirish
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: 'Email band' });
}
// Parolni hash qilish
const hashedPassword = await bcrypt.hash(password, 10);
// Yangi foydalanuvchi
const user = new User({
name,
email,
password: hashedPassword
});
await user.save();
// JWT yaratish
const token = jwt.sign(
{ userId: user._id },
'secret-key',
{ expiresIn: '7d' }
);
res.status(201).json({ token, user: { id: user._id, name, email } });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Login
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
// Foydalanuvchini topish
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ message: 'Email yoki parol xato' });
}
// Parolni tekshirish
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: 'Email yoki parol xato' });
}
// JWT yaratish
const token = jwt.sign(
{ userId: user._id },
'secret-key',
{ expiresIn: '7d' }
);
res.json({
token,
user: { id: user._id, name: user.name, email: user.email }
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
Auth Middleware
// middleware/auth.js
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Token yo\'q' });
}
const decoded = jwt.verify(token, 'secret-key');
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).json({ message: 'Noto\'g\'ri token' });
}
};
⚠️ Xavfsizlik
Production'da SECRET_KEY'ni .env faylida saqlang va hech qachon GitHub'ga yuklang!
7. Environment Variables
Muhim ma'lumotlarni .env faylida saqlash.
npm install dotenv
# .env
PORT=3000
MONGODB_URI=mongodb://localhost:27017/myapp
JWT_SECRET=your-secret-key-here
NODE_ENV=development
// server.js
require('dotenv').config();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET;
8. Loyiha strukturasi
my-api/
├── config/
│ └── database.js
├── controllers/
│ ├── authController.js
│ └── userController.js
├── middleware/
│ ├── auth.js
│ └── errorHandler.js
├── models/
│ └── User.js
├── routes/
│ ├── auth.js
│ └── users.js
├── .env
├── .gitignore
├── package.json
└── server.js
✅ Best Practices
- Har doim environment variables ishlating
- Error handling'ni to'g'ri qiling
- Validation qo'shing (express-validator)
- Rate limiting qo'shing (express-rate-limit)
- CORS sozlang (cors paketi)
- Helmet.js bilan xavfsizlikni oshiring
- Morgan bilan logging qiling
- API'ni versiyalang (/api/v1/)
Xulosa
Node.js va Express.js bilan professional backend yaratish uchun bu asoslar yetarli. Endi siz:
- REST API yarata olasiz
- MongoDB bilan ishlay olasiz
- JWT authentication qo'sha olasiz
- Middleware'larni tushunasiz
- Loyihani to'g'ri strukturalashni bilasiz
Keyingi bosqichlar:
- Testing (Jest, Supertest)
- Deployment (Heroku, DigitalOcean, AWS)
- GraphQL o'rganish
- Microservices arxitekturasi