虽然您的代码没有任何明显的错误,但它需要调试并与项目中的其他文件正确链接。
使用示例代码仔细检查以下文件:
route
是否在您的路由器文件中正确导出:// routes/subscribe.js
const express = require('express');
const router = express.Router();
const { subscribeletter } = require('../controllers/subscribeController');
router.post('/subscribe', subscribeletter);
module.exports = router;
routes/routes.js
中确保您正确加载和注册路线文件。// routes/routes.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();
const routesDirectory = path.join(__dirname);
fs.readdirSync(routesDirectory).forEach((file) => {
if (file.endsWith('.js') && file !== 'routes.js') {
const route = require(path.join(routesDirectory, file));
const routePath = `/${file.replace('.js', '')}`;
router.use(routePath, route);
}
});
module.exports = router;
app.js
/server.js
/index.js
确保以下模式:// app.js or server.js
const express = require('express');
const app = express();
const routes = require('./routes/routes'); // Dynamically loaded routes
app.use(express.json()); // Middleware for parsing JSON bodies
app.use('/api', routes); // All routes under /api
app.listen(3000, () => {
console.log('Server running on port 3000');
});
这将确保您在路线上收听
POST /api/subsribe
我希望这有帮助!