当前位置: 代码迷 >> JavaScript >> 将var从js传递到节点
  详细解决方案

将var从js传递到节点

热度:64   发布时间:2023-06-12 14:09:53.0

我有一个按钮,当按下该按钮时,我希望它将对象数组(日志)从该js文件发送到节点js文件,以便随后输出JSON文件。 我已经在 尝试过AJAX,但我仍然不明白如何在js和node之间传递变量。

 const done_but = document.getElementById("done"); var logs = [] var xhttp = new XMLHttpRequest(); document.getElementById('r2').checked = true; done_but.onclick = function() { const student = document.getElementById("student-drop").value; const face = document.querySelector('input[name="faceses"]:checked').value; const time = new Date(); logs.push([{ student: student, face: face, time: time.toUTCString() }]); xhttp.open("POST", "file:///(file path)/index.html"); xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); xhttp.send(logs); console.log(logs); }; 

我发现,如果您将样式和本地js放入HTML文件中,则可以将其写入屏幕,然后从本地js获取任何输入。 要提供服务器数据,您可以

 var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://localhost:8000"); xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); xhttp.send(YourVar); 

这是我的节点代码,接受输入并编写屏幕。

 var http = require('http'); var fs = require('fs'); http.createServer(function(req, res) { fs.readFile('index.html', function(err, data) { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(data); res.end(); if (req.method === 'POST') { let body = ''; req.on('data', chunk => { body += chunk.toString(); // convert Buffer to string }); req.on('end', () => { console.log(body); console.log(""); res.end('ok'); }); } }); }).listen(8000); 

有用的链接:

  相关解决方案