1

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 "{}"

3 Answers 3

3

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});
    })   
  })
Sign up to request clarification or add additional context in comments.

Comments

1

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});
   })
})

Comments

1

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
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.