如何将数据从 Node.js 传递到 javascript

How to pass data from Node.js to javascript

作为任务的一部分,我正在尝试从我的 javascript 中的 Node.js 获取数据。

node.js

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

javascript 文件是 index.ejs 中的链接脚本。

js

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

我希望每当调用 'pullLever' 函数时,警报响应中都会包含五 (5) 个,但是对于此代码,响应只是一个空字典 ({}),任何帮助都会很大赞赏

JSON.stringify(response,null,4) returns {} 因为 response 不是 return 响应主体,而是 Response object. if what you want is get the response body, you should Response.text() it (or Response.json() 它)。

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

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

以及为什么 Response 对象不能被字符串化?响应的字段是 private我猜.

对于您的 nodejs,您将 res.send 与 int 一起使用。请阅读这个答案:

对于 nodejs,你会有这样的东西:

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

在你的文件中:

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

编辑:经过测试,您 alert 时的输出应该是 [object object]5 注释掉的行 res.send('5');如果您不使用 nodemon 或类似的,请不要忘记在更改后重新启动服务器。