简体   繁体   中英

How to link routes with controllers in node js?

I have some API's written in server.js. I want to make MVC structure like i want to have all routes in routes directory and APIs in controller. How i can make this structure with koa and nodejs. I'm new in nodejs. I try to do something but its not working. How to link all this with server.js. So that when i start the server APIs should work. Hope you understand my question. I tried many things but not working for me.

Controllers: apiController.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());

Routes: api.js

const Router = require('koa-router');
const router = new Router();
const apiController = require('../controllers/ApiController');


router.get("/api/get_all_users", apiController);

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,
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});



Live Demo : 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');
    });

Next, create folder modules and sub folders like as below :

  • user-management
    • routes
      • router.js
      • user.js
    • controller
      • user.js
    • models
      • user.js

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM