我在server.js中编写了一些API。我想使MVC结构像我想要在路由目录中的所有路由和控制器中的API。我如何使用koa和nodejs制作此结构。我是nodejs的新手。我尝试做某事,但是不起作用。如何将所有这些与server.js链接。这样,当我启动服务器API时就可以使用。希望你理解我的问题。我尝试了很多事情,但没有为我工作。
控制器:apiController.js
0
路由:api.js
const Router = require('koa-router');
const router = new Router();
const Koa = require('koa');
const app = new Koa();
var bodyParser = require('koa-bodyparser');
app.use(bodyParser({
formidable: {uploadDir: './uploads'},
multipart: true,
urlencoded: false
}));
router.get('/api/get_all_users', async (ctx) => {
const {rows} = await ctx.app.pool.query('SELECT * from users');
ctx.body = {
status: 200,
message: "Data Found",
data: rows,
};
});
app.use(router.routes()).use(router.allowedMethods());
Server.js
const Router = require('koa-router');
const router = new Router();
const apiController = require('../controllers/ApiController');
router.get("/api/get_all_users", apiController);
答案 0 :(得分:1)
实时演示: Node Server
server.js
const Koa = require('koa');
const app = new Koa();
const {Pool} = require('pg');
app.pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'my_db',
password: 'my_pass',
port: 5432,
});
// initialize user management module
require('./modules/user-management/routes')(app)
app.listen(3000, () => {
console.log('Server running on port 3000');
});
接下来,创建文件夹模块和子文件夹,如下所示:
modules-> user-management-> routes-> router.js
router.js
module.exports = (app) => {
// user-routes api file.
require("./user")(app);
};
modules-> user-management-> routes-> user.js
var UserControl = require("../controller/user");
module.exports = function (app) {
const endpoint = "api";
app.post(endpoint+"get_all_users",UserControl.getAllUsers);
};
modules-> user-management-> controller-> user.js
var userControl = {
getAlluser: async (req, res) => {
try {
// get functionality here..
let users=[{'uid':1,'uname':'rahul'}]
res.status(200).json(users);
} catch (err) {
res.status(500).json(err);
}
}
}
module.exports = userControl;