Post data from client to Node server

Multi tool use
Post data from client to Node server
I can post data to node server though i can't access the data in my app.get route.
orders.hbs (ajax):
$.post( "/show_items", { o_id: result } );
app.js:
app.post ('/show_items', function(req,res){
var order_num = req.body.o_id;
});
app.get('/orders',authenticationMiddleware(), function(request, response){
console.log(order_num);
...
}
The problem is that in my app.get i can't access the $order_num variable. How can i access the variable and use it?
2 Answers
2
I want to know the use-case before answering. As you sent the data in POST-API, it should ideally be available/used by all middlewares (functions) defined to POST-API.
@Yoni: You are trying to use info passed in POST API (under property req.body.order_num) in altogether different GET API.
But if you want to access it anyway then solution shared by @Bostrot works fine.
while invoking GET API, pass the row_id as
htttp://domain_name.com/v1/path/endpoint?row_id=12
In server code (In API), fetch and use row_id as var row_id = req.query.row_id
– ravi_kumar_yadav
Jul 3 at 14:11
htttp://domain_name.com/v1/path/endpoint?row_id=12
var row_id = req.query.row_id
As order_num
gets defined in app.post
it is a local variable and only available under that scope. If you want to access it in app.get
you need to define it before and then just set it:
order_num
app.post
app.get
var order_num;
app.post ('/show_items', function(req,res){
order_num = req.body.o_id;
});
...
app.get('/orders',authenticationMiddleware(), function(request, response){
console.log(order_num);
}
Hi thanks, though for some reason order_num doesn't save its change after app.post. So i am still stuck.
– Yoni Harris
Jul 2 at 12:58
It most likely does. I guess what you are encountering is that
app.get
is called before order_num
has a value. You should consider putting the app.get
request somewhere where you are sure that it already has a value like in app.post
direclty.– Bostrot
Jul 2 at 13:01
app.get
order_num
app.get
app.post
I assume you are correct. My problem is that I want that data to constantly change. When the user clicks the row on the table, ajax sends a post to app.js and the variable order_num changes. How can that be done?
– Yoni Harris
Jul 2 at 15:33
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi, I have an html page with a table. I would like that when the user clicks on a row, it sends the id of the row to app.get route in my app.js node server.
– Yoni Harris
Jul 2 at 12:58