如何将数据从Node.js传递到javascript
作为任务的一部分,我正在尝试从javascript中的Node.js获取数据 node.js如何将数据从Node.js传递到javascript,javascript,node.js,express,ejs,Javascript,Node.js,Express,Ejs,作为任务的一部分,我正在尝试从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 functi
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)
返回{},因为response
不是返回响应体,而是对象。如果你想要的是得到响应体,你应该得到它
constpulllever=async函数(){
const response=wait fetch('/calculateResult');
const text=等待响应。text();
警报(JSON.stringify(response,null,4));
}
或
const response=wait fetch('/calculateResult')。然后((val)=>val.text();
为什么响应对象不能字符串化?响应的字段为。我猜。JSON.stringify(response,null,4)返回{},因为response
不是返回响应体,而是对象。如果你想要的是得到响应体,你应该得到它
constpulllever=async函数(){
const response=wait fetch('/calculateResult');
const text=等待响应。text();
警报(JSON.stringify(response,null,4));
}
或
const response=wait fetch('/calculateResult')。然后((val)=>val.text();
为什么响应对象不能字符串化?响应的字段为。我猜。对于您的节点,请使用带有int的
res.send
。请阅读以下答案:
对于nodejs,您将有如下内容:
“严格使用”;
app.get('/calculateResult',函数(req,res,next){
res.json({myNumber:5});
//或res.send('5');
});
在您的文件中:
//编辑:这将是您的杠杆功能。
(异步()=>{
let res=等待获取(“http://127.0.0.1:4000/calculateResult");
res.json().then(函数(数据){
console.log(数据);//检查控制台的输出
});
})();
编辑:已测试,对于注释掉的行
res.send('5')
,当您发出alert
时,您的输出应该是[object object]
和5
;如果您没有使用nodemon
或类似工具,请不要忘记在更改后重新启动服务器。对于您的nodejs,请使用带有int的res.send
。请阅读以下答案:
对于nodejs,您将有如下内容:
“严格使用”;
app.get('/calculateResult',函数(req,res,next){
res.json({myNumber:5});
//或res.send('5');
});
在您的文件中:
//编辑:这将是您的杠杆功能。
(异步()=>{
let res=等待获取(“http://127.0.0.1:4000/calculateResult");
res.json().then(函数(数据){
console.log(数据);//检查控制台的输出
});
})();
编辑:已测试,对于注释掉的行res.send('5')
,当您发出alert
时,您的输出应该是[object object]
和5
;如果您没有使用nodemon
或类似工具,请不要忘记在更改后重新启动服务器