Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139833

How to link routes with controllers in node js?

$
0
0

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 API's 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 API's should work. Hope you understand my question.

Controllers: apiController.js

const Router = require('koa-router');
const router = new Router();
const Koa = require('koa');
const app = new Koa();
const Logger = require('koa-logger');
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(Logger());
// Add routes and response to the OPTIONS requests
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');
});




Viewing all articles
Browse latest Browse all 139833

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>