Tuesday 11 April 2017

How to avoid the ambiguity of routes in Express.js

I have three files server.js, views.js and access.js

In server.jsI have put all the dependencies and some routes like

app.post('/services/getallversions', (req, res) => {
... 
// code to handle the req and send response
})

In views.js I have code like below,

module.exports = function(app, db, bodyParser, rules, constants, query) {

app.post('/services/user/:user/:type', (req, res) => {
// user can be 'abcd'
// type can be addview, deleteview etc.

...
// do processing for the req and send res
})


}

In access.js I have code like,

module.exports = function(app, db, bodyParser, rules, constants, query) {

app.post('/services/user/:user/:type', (req, res) => {
// user can be 'abcd'
// type can be addaccess, removeaccess etc.

...
// do processing for the req and send res
})


}

In server.js file I require the access.js and views.js in following way,

var access = require('./access')(app, db, bodyParser, rules, constants, query)
var views = require('./views')(app, db, bodyParser, rules, constants, query)

When I try to POST using /services/user/abcd/addaccess my views.js file code gets executed. constants, query, rules are other .js file which is already used in server.js using require('./filename').

I understand that the ambiguity causes due to same URL structure. I am using Express 4 and Node JS 6. I want to separate code of access.js and views.js from server.js and put them in separate files and require them in the above mentioned manner. views.js and access.js are created by me. They are not any Javascript Framework or something like that.

In view.js I have also tried the following code

var router = require('express').Router()

router.post('/services/user/:user/:type', (req,res)=>{})

But the same problem exists. Is there any way to achieve the thing ?



via Anijit

No comments:

Post a Comment