如何将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
相关产品推荐
相关产品推荐

