Caleb Bird
Caleb Bird

Reputation: 65

NodeJS res.send not returning variable value

I'm working on a NodeJS/Express program and I'm trying to get a POST request to return data. When I return a direct string, I get the correct response.

app.post("/DoStuff", function(req, res, Data) {
  DoStuf.DoStuffFunction(req.body.UserID, function(label) {
    Data = label
    })
    res.send({message: "Stuff"});
  })

When I change it to return a variable (which is still a string) it only returns "{}".

app.post("/DoStuff", function(req, res, Data) {
  DoStuf.DoStuffFunction(req.body.UserID, function(label) {
    Data = label
    })
    res.send({message: Data});
  })

Even when I make Data = "foo" the response is "{}"

Upvotes: 1

Views: 5436

Answers (3)

Sridhar
Sridhar

Reputation: 11796

When I change it to return a variable (which is still a string) it only returns "{}".

This is because DoStuf.DoStuffFunction(){} is asynchronous.

The reason why it works when you use stuff as value is because the operation is synchronous. And you have value with you before sending the response.

If you want to send response only after the DoStuffFunction() completes, place the response.send() within the callback.

'use strict';

app.post("/DoStuff", function(req, res, Data) {
  DoStuf.DoStuffFunction(req.body.UserID, function(label) {
    res.send({message: label}); //you can send label's value directly
    });
});

Upvotes: 1

Vasyl Moskalov
Vasyl Moskalov

Reputation: 4650

Looks like your DoStuffFunction is async. So just move res.send(..) in callback.Something like

app.post("/DoStuff", function(req, res, Data) {
  DoStuf.DoStuffFunction(req.body.UserID, function(label) {
    res.send({message: label});
   })
})

Upvotes: 1

Suresh Prajapati
Suresh Prajapati

Reputation: 4477

You need to send from inside of callback function. In your code res.send is independent of DoStuffFunction's callback

app.post("/DoStuff", function(req, res, Data) {
  DoStuf.DoStuffFunction(req.body.UserID, function(label) {
    Data = label;
    res.send({message: Data});
    })   
  })

Upvotes: 3

Related Questions