0

I'm trying to build an application will allow me to take a String parameter from the frontend, and create an Express route from that. Is that possible?

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

router.post('/newAPI/:name', function(req, res, next) {
    var name = req.params.name;
    router.get('/'+name, function(req, res, next) {
        res.send({"name":""+name});
    });
});

With this, would calling localhost:3000/newApi/bob create a new route localhost:3000/bob that returns {"name":"bob"}?

5
  • 1
    What are you trying to accomplish? That route will not exist if you restart the application. It would be better to save the route info in persistent storage and create the routes using the stored values. Commented Apr 13, 2017 at 20:51
  • 1
    I believe that it would "work" as in your example but it should be easy to test :) Commented Apr 13, 2017 at 20:53
  • 1
    This is pretty much never the right way to solve a problem because each .post() that occurs creates a duplicate .get() handler. And, because none of this is remembered when your server is restarted. To get advice on a better way to solve the problem, you should describe your actual design goal and we can help with a better way to do this. Commented Apr 13, 2017 at 20:59
  • @doublesharp and all, thank you for the confirm. Yes, I had not realized the restart will erase my progress so I will probably have to build in some memory capability, probably through MongoDB. As for the end goal, I am trying to make an API creator. Commented Apr 14, 2017 at 0:28
  • 1
    The correct implementation is going to be somewhat more complex - dynamically load the route and save it at the same time, load the routes from storage when the app starts, etc. Since there is probably some business logic you could use /:route and then use the req.params.route as a key to lookup that route definition, or return an error if it doesn't exist. Commented Apr 14, 2017 at 0:41

1 Answer 1

1

It will work, unless you restart the application.

Also, just use {"name": name}.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you should say it will "work" because while it may seem to behave as expected at first this is not a good implementation.

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.