简体   繁体   中英

Multiple level of routing using Express.js with Node.js

I'm new to javascript. I'm trying to make a RESTfull API using Node.js and Express.js

My directory structure is as follows

/server.js

/api/api.js

/api/location/location.js

I want to make the API modular. I want that all the requests (get/post/delete/push) beginning with /api/* to be handled by api.js and whatever routing be required, api.js should route it to proper module.

For example, if someone requests GET /api/location/abc/xyz then api.js will transfer control to location.js which will then transfer to abc.js which will finally transfer to xyz.js stored in directory /api/location/abc/xyz/xyz.js

How can I achieve this?

Code so far:

/server.js

var express  = require('express');
var app      = express();

var api      = require('./api/api.js');
var location = require('./api/location/location.js');

//app.use('/api/location', location); //This works, but I want api.js to handle sub-routes!

app.use('/api', api);

app.get('/', function(req, res){
    res.end('successful get/');
});

app.listen(12345);

/api/api.js

module.exports = function(req, res, next) {
    res.end('successful get /api');
    next();
};

//Add code to handle GET /api/location

/api/location/location.js

module.exports = function(req, res, next){
    res.end('from location!');
    next();
}

You would use express.Router([options]) .

And write it that way:

/api/api.js

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

router.get('/location', require('./api/location') );

module.exports = router;

/api/api/location.js

module.exports = function(req, res, next){
   res.end('from location!');
}

And don't call next(); if you ended the response. You only call next() in your callback if you don't handle the response.

I don't know how complex your REST api will be later. But try to to keep the routing in a small number of file. Having a callback for the routing in an own file like /api/api/location.js is most likely not the best idea.

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