将路由分成不同的模块

问题描述 投票:0回答:1

我一直将所有路由放入一个 server.js 文件中,过了一会儿我意识到一个文件中有大约 1000 行,并且很难管理它。问题是有没有一种简单的方法可以将这些路由分成不同的路由文件,而不必重写所有内容?这是我的代码片段,不会放置整个代码,它会占用太多空间

const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('school_canteen', 'root', 'password', {
 host: 'localhost',
 dialect: 'mysql'
});

const db = require('./db');
// const childrenRoutes = require('./routes/children');
const { User } = require('./models');
const { Order } = require('./models');
const menuitems = require('./models/menuitems');
const productCategory = require('./models/productCategory');
const Deal = require('./models/deal')(sequelize, DataTypes);
const { Product, ProductCategory, Menu,MenuItem } = require('./models');

const app = express();
const PORT = process.env.PORT || 3001;

app.use(cors());
app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

const storage = multer.diskStorage({
 destination: function (req, file, cb) {
   cb(null, 'uploads/');
 },
 filename: function (req, file, cb) {
   cb(null, `${Date.now()}-${file.originalname}`);
 }
});
const upload = multer({ storage: storage });

sequelize.sync().then(() => {
 console.log('Database synchronized');
}).catch(error => {
 console.error('Error synchronizing the database:', error);
});

const Photo = sequelize.define('Photo', {
 PhotoID: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
 photoUrl: { type: Sequelize.STRING, allowNull: false },
 productId: { type: Sequelize.INTEGER, allowNull: false },
 altText: { type: Sequelize.STRING, allowNull: true }
}, {
 tableName: 'photos'
});


const Child = sequelize.define('Child', {
 Name: { type: Sequelize.STRING, allowNull: false },
 Surname: { type: Sequelize.STRING, allowNull: false },
 Grade: { type: Sequelize.STRING, allowNull: false },
 UserID: { type: Sequelize.INTEGER, allowNull: false }
}, {
 tableName: 'children'
});

const authenticateToken = (req, res, next) => {
 const authHeader = req.headers['authorization'];
 const token = authHeader && authHeader.split(' ')[1];
 
 console.log('Token received:', token);

 if (token == null) return res.sendStatus(401);

 jwt.verify(token, 'your_secret_key_here', (err, user) => {
   if (err) {
     console.error('Token verification failed:', err);
     return res.sendStatus(403);
   }
   req.user = user;
   console.log('User from token:', user);
   next();
 });
};

const isAdmin = async (req, res, next) => {
 try {
   const user = await db.User.findByPk(req.user.id);
   if (user && user.RoleID === 2) {
     next();
   } else {
     res.sendStatus(403);
   }
 } catch (err) {
   res.sendStatus(500);
 }
};

app.post('/api/admin/photos', authenticateToken, isAdmin, upload.single('photo'), async (req, res) => {
 const { productId, altText } = req.body;
 const photoUrl = req.file ? req.file.path : undefined;

 console.log('Request Body:', req.body);
 console.log('Uploaded File:', req.file);

 if (!productId || !photoUrl) {
   return res.status(400).json({ error: 'ProductID and PhotoURL are required' });
 }

 try {
   const newPhoto = await Photo.create({
     photoUrl,
     productId,
     altText
   });
   res.status(201).json(newPhoto);
 } catch (err) {
   console.error('Error creating photo:', err);
   res.status(500).send('Server Error');
 }
});

app.put('/api/admin/photos/:photoId', authenticateToken, isAdmin, upload.single('photo'), async (req, res) => {
 const { photoId } = req.params;
 const { productId, altText } = req.body;
 const photoUrl = req.file ? req.file.path : undefined;

 try {
   const photo = await Photo.findByPk(photoId);
   if (!photo) return res.status(404).json({ msg: 'Photo not found' });

   photo.productId = productId || photo.productId;
   photo.altText = altText || photo.altText;
   if (photoUrl) { 
     photo.photoUrl = photoUrl;
   }
   await photo.save();
   res.json(photo);
 } catch (err) {
   console.error(err.message);
   res.status(500).send('Server Error');
 }
});

app.delete('/api/admin/photos/:photoId', authenticateToken, async (req, res) => {
 const { photoId } = req.params;

 try {
   const photo = await Photo.findByPk(photoId);
   if (!photo) {
     return res.status(404).json({ error: 'Photo not found' });
   }

   await photo.destroy();
   res.status(200).json({ message: 'Photo deleted successfully' });
 } catch (error) {
   console.error('Error deleting photo:', error);
   res.status(500).json({ error: 'Failed to delete photo' });
 }
});


app.get('/api/photos', authenticateToken, async (req, res) => {
 try {
   const photos = await Photo.findAll();
   res.json(photos);
 } catch (error) {
   console.error('Error fetching photos:', error);
   res.status(500).json({ error: 'Failed to fetch photos' });
 }
});

app.get('/photos/:productId', authenticateToken, async (req, res) => {
 try {
   const photos = await Photo.findAll({ where: { productId: req.params.productId } });
   res.json(photos);
 } catch (err) {
   console.error('Error fetching photos:', err.message);
   res.status(500).send('Server Error');
 }
});
app.listen(PORT, () => {
 console.log(`Server running on port ${PORT}`);
});
javascript node.js express sequelize.js
1个回答
0
投票

创建一个 Routes 文件夹并在其中创建路线文件

// Routes
const adminRoute = require('./Routes/Admin');
const photoRoute = require('./Routes/Photos');

并将其添加到您的 main.js 中,例如代码片段。 之后也请添加此内容,以便快递管理您的请求。

// Routers
app.use('/admin', adminRoute);
app.use('/photo', photoRoute);

你的一个路线文件应该是这样的

//Library
const express = require('express');

const router = express.Router();

//Routes
router.post('/photo' , yourEndpointFunction);
router.post('/anything' , yourEndpointFunctionComesHere);

module.exports = router;

也将端点函数放在这里,您也可以从另一个文件中提取该函数。

© www.soinside.com 2019 - 2024. All rights reserved.