我尝试将控制器添加到我的项目中,但无法调整我的异步/等待语法。
我的NodeJs / Express项目具有以下结构:
controllers/
categories.js
models/
category.js
routes/
categoryRoutes.js
services/
db.js
app.js
package.json
categoryRoutes.js 路线:
const express = require('express');
const router = express.Router();
// Controlller
const CategoryController = require('../controllers/categories');
router.post('/get-all', CategoryController.getAll); // This is where the app fails
categories.js 控制器:
// Model
const Category = require('../models/category');
exports.getAllCategories = async (req, res, next) => {
const result = await Category.getAll();
next();
}
category.js 模型:
var db = require('../services/db');
exports.getAll = async () => {
const categories = await db.get().query('SELECT * FROM categories');
next(null, categories);
}
代码在categoryRoutes.js文件中产生以下错误:
**\node_modules\express\lib\router\route.js:202
[0] throw new Error(msg);
[0] ^
[0]
[0] Error: Route.post() requires a callback function but got a [object Undefined]
[0] at Route.(anonymous function) [as post] (**\node_modules\express\lib\router\route.js:202:15)
[0] at Function.proto.(anonymous function) [as post] (**\node_modules\express\lib\router\index.js:510:19)
[0] at Object.<anonymous> (**\routes\categoryRoutes.js:53:8)
[0] at Module._compile (module.js:660:30)
[0] at Object.Module._extensions..js (module.js:671:10)
[0] at Module.load (module.js:573:32)
[0] at tryModuleLoad (module.js:513:12)
[0] at Function.Module._load (module.js:505:3)
[0] at Module.require (module.js:604:17)
[0] at require (internal/module.js:11:18)
[0] at Object.<anonymous> (**\app.js:126:24)
[0] at Module._compile (module.js:660:30)
[0] at Object.Module._extensions..js (module.js:671:10)
[0] at Module.load (module.js:573:32)
[0] at tryModuleLoad (module.js:513:12)
[0] at Function.Module._load (module.js:505:3)
在Router.get / post中使用 Async / Await 控制器/模型函数的正确方法是什么??