zinkking/project2-nodejs
0
1require('dotenv').config();2const express = require('express');3const mongoose = require('mongoose');4const cors = require('cors');5const path = require('path');6 7const app = express();8 9// --- QUAN TRỌNG: Hugging Face bắt buộc dùng Port 7860 ---10const PORT = 7860; 11 12// Middleware13app.use(cors());14app.use(express.json());15app.use(express.static(path.join(__dirname, 'public')));16 17// Kết nối MongoDB18const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/studentdb';19 20mongoose.connect(MONGO_URI)21 .then(() => console.log('✅ Đã kết nối MongoDB'))22 .catch(err => console.error('❌ Lỗi kết nối MongoDB:', err));23 24// --- MODEL ---25const StudentSchema = new mongoose.Schema({26 code: String,27 name: String,28 department: String29});30const Student = mongoose.model('Student', StudentSchema);31 32// --- ROUTES ---33// 1. Lấy danh sách34app.get('/api/students', async (req, res) => {35 try {36 const students = await Student.find();37 res.json(students);38 } catch (err) {39 res.status(500).json({error: err.message});40 }41});42 43// 2. Thêm mới44app.post('/api/students', async (req, res) => {45 try {46 const newStudent = new Student(req.body);47 await newStudent.save();48 res.json(newStudent);49 } catch (err) {50 res.status(500).json({error: err.message});51 }52});53 54// 3. Xóa55app.delete('/api/students/:id', async (req, res) => {56 try {57 await Student.findByIdAndDelete(req.params.id);58 res.json({message: 'Deleted'});59 } catch (err) {60 res.status(500).json({error: err.message});61 }62});63 64// Route trang chủ (Catch-all route phải để cuối cùng)65app.get(/.*/, (req, res) => { 66 res.sendFile(path.join(__dirname, 'public', 'index.html'));67});68 69// Lắng nghe tại cổng 786070app.listen(PORT, () => {71 console.log(`🚀 Server đang chạy tại http://localhost:${PORT}`);72});