Gagiu Filip Gagiu Filip - 6 months ago 110
Node.js Question

Node.js var does not save

ok so i have this code for a Microsoft QnA Bot, i have that let message variable global and i need to save it.Problem is it does not...if i run a console.log inside the function on message everything is fine but outside the message is back to normal...What am i suppose to do?Thank you!

let message = "?"; ///my var global

app.post('/send',upload.any(),function (req,res,next) {
// Post event
const translated = JSON.stringify({"question": req.body.message});
const extServerOptionsPost = {
host: 'westus.api.cognitive.microsoft.com',
path: 'https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases//generateAnswer',
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': '',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(translated)
}
};

const reqPost = http.request(extServerOptionsPost, function (res) {
console.log("response statusCode: ", res.statusCode);
res.on('data', function (data) {
process.stdout.write("JSON.parse(data).answers[0].answer");
message = JSON.parse(data).answers[0].answer;
console.log(message);//Everything is fine!
});
});
reqPost.write(translated); // calling my function
console.log(message)// not fine anymore :(
res.render('Bot',{quote:"no question"});
});

Answer Source

There are a few ways to actually fix this...but the quickest way is to utilize async/await.

app.post('/send',upload.any(),async function (req,res,next) {
// Post event
    const translated = JSON.stringify({"question": req.body.message});
    const extServerOptionsPost = {
        host: 'westus.api.cognitive.microsoft.com',
        path: 'https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases//generateAnswer',
        method: 'POST',
        headers: {
            'Ocp-Apim-Subscription-Key': '',
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(translated)
        }
    };

    const reqPost = await http.request(extServerOptionsPost, function (res) {
        console.log("response statusCode: ", res.statusCode);
        res.on('data', function (data) {
            process.stdout.write("JSON.parse(data).answers[0].answer"); 
            message = JSON.parse(data).answers[0].answer;
            console.log(message);//Everything is fine!
        });
    });
    reqPost.write(translated); // calling my function
    console.log(message)// not fine anymore :(
    res.render('Bot',{quote:"no question"});
});

Changes:

app.post('/send',upload.any(),function (req,res,next) {
to
app.post('/send',upload.any(),async function (req,res,next) {

and

const reqPost = http.request(extServerOptionsPost, function (res) {
to
const reqPost = await http.request(extServerOptionsPost, function (res) {

It's also recommended to add some error handling with this process by wrapping the await within a try{}catch(e){}.

More info on promises here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download