2

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!

1
  • 1
    Take a look at doc - I'm assuming you use express and route path can have mini regex-like matching where you can name parameter, make it optional or selective, etc... Commented Dec 16, 2015 at 23:57

2 Answers 2

2

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()
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.