Ike Anya
Ike Anya

Reputation: 201

How to pass data from Node.js to javascript

I am trying to get data from Node.js in my javascript as part of a task.

The node.js

app.get('',(req,res)=>{
    res.render('index.ejs')
})
app.get('/calculateResult',(req,res)=>{
    console.log(id)
    res.send(5)
})

The javascript file is a linked script in the index.ejs.

The js

const pullLever = async function(){
    let response = await fetch('/calculateResult')
    alert(JSON.stringify(response,null,4))
}

I expect five(5) to be contained in the alert response whenever the 'pullLever' function is called, but with this code the response is just an empty dictionary({}), any help will be much appreciated

Upvotes: 0

Views: 1594

Answers (2)

ziaahsan
ziaahsan

Reputation: 34

For your nodejs, your using res.send with int. Please read this answer: how to send int

For nodejs, you would have something like:

"use strict";
app.get('/calculateResult', function (req, res, next) {
    res.json({myNumber: 5});
    // or res.send('5');
});

And in your file:

// Edit: This would be your lever function.
(async () => {
      let res = await fetch("http://127.0.0.1:4000/calculateResult");
      res.json().then(function(data) {
         console.log(data); // Check console for output
      });
})();

Edit: Tested, your output for when you alert should be [object object] and 5 for the commented out line res.send('5'); If your not using nodemon or similar, don't forget to restart your server after changes.

Upvotes: 1

nouvist
nouvist

Reputation: 1182

the JSON.stringify(response,null,4) returns {} because response is not return response body, but Response object. if what you want is get the response body, you should Response.text() it (or Response.json() it).

const pullLever = async function() {
    const response = await fetch('/calculateResult');
    const text = await response.text();
    alert(JSON.stringify(response, null, 4));
}

or

const response = await fetch('/calculateResult').then((val) => val.text());

and why does Response object can't be stringified? Response's fields is private. I guess.

Upvotes: 1

Related Questions