Valentin H
Valentin H

Reputation: 7438

Dynamic routing in Node.js

I want to create dynamic stubs as webservices. My idea is to load at every request a definition file and return data for corresponding URL. The definition file could look like this:

/api/users {users:["john", "jack", "jake"]}
/api/users/1 {user:"john"}
/api/some-data/1 {data:"some data"}

In an application I created on behalf of a tutorial I find:

router.post('/some-irl', function (req, res) {
    //some code
    return {some JSON}
});

But this definition looks static to me, which should be there before I start Node.js Is it possible to define /some-irl at the time then request occures?

EDIT

Actually, I was intending to do somehting like this: https://github.com/typicode/json-server but it is already there!

Upvotes: 2

Views: 510

Answers (2)

TbWill4321
TbWill4321

Reputation: 8666

You can attach a use middleware, which can check the path and decide whether to handle it or pass it on:

router.use(function(req, res, next) {
    // req.path
    // decide what to do
    // respond or next()
});

Upvotes: 2

Nir Levy
Nir Levy

Reputation: 12953

you can define variables in the routes, use : before the variable name to define it, and then you'll get the value in req.params:

route.get('/api/users/:user/', function (req, res) {
   var username = req.params.user;
});

Upvotes: 1

Related Questions