0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.