Nodejs get api parameter not updated after first call

I have a function where after a post request is made, a get api call has to be made. I tried implementing this by calling a function from post.

app.post('/',function(req,res){
   res.send(req.body);
   callGet(req.body)
})

function callGet(value){              // value updated after every call
 app.get('/val',function(req,res){
     getVal(value);                  // value doesn't update after first call
function getVal(value){
 #do something
}
res.send(resultFrom_getVal)
})
}

The parameter passed from post gets updated in callGet(value) after every call but isn't reflected inside getVal(value) after FIRST call. So, after every post, it renders for the first post call parameters. Please correct me if my way of implementation is wrong, I am new in using REST api.

1 answer

  • answered 2021-07-27 18:25 jfriend00

    All your function callGet() is doing is registering a route. It isn't calling that route. And, even if it was, you'd be trying to send two responses to the same request which you also can't do. You get one response for each incoming request.

    You should also never be registering a route in a route handler either as they will just pile up every time the top level route is triggered.

    If what you're trying to do is to execute the same code from two different routes, then just create a common Javascript function (not a route) that you can call from both routes. That function can process some data and return the result which each route can then use in sending its own response.

    If what you're trying to do is pass data from the POST request to some subsequent request, then there are several options:

    1. You can redirect to the GET request and pass the data as a query parameter in the URL.
    2. You can store the data in a server-side session so upon the next /val GET request from that client, the route can get the data from the server-side session object for that particular client and use it in the processing of the GET request. This breaks the general theory of a REST API since what a GET request returns will depend upon something that happened before it rather than fetching the same resource every time (so this won't be RESTful).
    3. You can return the data back to the client from the POST and the client can save the data and use it as a parameter on a future GET request. This could be RESTful if implemented properly. This also avoids storing server-side state which is generally desirable where possible.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum