Paweł Baca
Paweł Baca

Reputation: 888

Request to other route in node.js

How can I make a request to another route in node.js? I have POST request and after successful POST request I want to do GET request to get date this user.

app.post("/childrens", checkUser, async (req, res, next) => {
    ...
    const childrenResponse = await Childrens.create({
            ...children,
            id_kindergarten,
            type: 2
        })
    //here I want make get request after successful POST request
    const data = app.get("/childrens/2");
    res.send(data);
}

Upvotes: 0

Views: 204

Answers (3)

Ravi Malviya
Ravi Malviya

Reputation: 121

Try like this, it working in my case.

app.use('/users', function(req, res, next){
  console.log('users');
});

app.use('/test', function(req, res, next){
  console.log('test');
  req.url = '/users';
  return app._router.handle(req, res, next);
});

output :

GET /test - - ms - -
test
users

Upvotes: 0

Alan Friedman
Alan Friedman

Reputation: 1610

Commonly this is handled with a 303 See Other including a Location header for the other resource. In your case:

res
  .set('Location', '/childrens/2')
  .status(303)
  .send();

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44107

Try using the handle method like so:

req.method = "GET";
req.url = "/childrens/2";
app._router.handle(req, res, next);

Upvotes: 3

Related Questions