1

app variable is defined by

const app = express();

This code is working fine:

app.get('/posts/:id', (req, res) => {
    res.json( post_creator.CreatePost(req.params.id) );
});

But the below code is not working:

const post_url_with_id = '/posts/:id';
app.get(post_url_with_id, (req, res) => {
    res.json( post_creator.CreatePost(req.params.id) );
});

How can i create function with parameter can pass express.get or post methods?

I want to implement like next function

function serve_post( post_url_with_id ) {
    app.get(post_url_with_id, (req, res) => {
        res.json( post_creator.CreatePost(req.params.id) );
    });
}

Thanks for contributors.

김진희
  • 11
  • 4

1 Answers1

0

This can be implemented by passing express app like:

// someRoute.js
function serve_post(app, post_url_with_id ) {
    app.get(post_url_with_id, (req, res) => {
        res.json( post_creator.CreatePost(req.params.id) );
    });
}

module.exports = serve_post;

In your file where you've instantiated express (where you have app)

const app = express();
// assuming they are in same folder
const someRoute = require('./someRoute');

someRoute(app, post_url_with_id);
1565986223
  • 6,420
  • 2
  • 20
  • 33