You need to enable JavaScript to run this app. 如何将JavaScript中的变量数据发送到Node.js后端服务
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript中的变量数据发送到Node.js后端服务

前端实现方案

以下是两种常用的前端发送数据到后端的实现方式,你可以根据场景选择:

方案1:Fetch API(现代浏览器推荐)

var roomurl = "this is the data";

fetch('/newcall', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    roomurl: roomurl
  })
})
.then(res => res.json())
.then(data => {
  // 按需补充请求成功后的逻辑
  console.log('数据发送成功,后端返回:', data)
})
.catch(err => {
  // 按需补充错误处理逻辑
  console.error('数据发送失败:', err)
})

方案2:XMLHttpRequest(兼容旧版浏览器)

var roomurl = "this is the data";
var xhr = new XMLHttpRequest();
xhr.open('POST', '/newcall', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 按需补充请求成功后的逻辑
    console.log('数据发送成功,后端返回:', xhr.responseText);
  }
};
xhr.send(JSON.stringify({roomurl: roomurl}));
注意事项
  • 确认你的Node.js服务已经开启了JSON解析配置,express 4.16+版本自带解析能力,直接加如下代码即可:
app.use(express.json())

如果是用单独安装的body-parser,配置代码如下:

const bodyParser = require('body-parser')
app.use(bodyParser.json())
  • 建议你调整后端接口,给前端返回明确响应,避免前端出现无响应的报错:
app.post("/newcall", function(req, res) {
  var n = req.body.roomurl;
  console.log("val"+ n);
  res.json({status: 'ok', receivedData: n})
});

内容的提问来源于stack exchange,提问作者deepak pal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 03:57:07