将 var 从 js 传递到 node



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

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);

有用的链接:如何发送 JSON 数据如何发送数据处理请求

最新更新