首页 > 解决方案 > passing vars from js to node

问题描述

I have a button that when pressed I want it to send an array of objects (logs) from that js file to a node js file so I can then output a JSON file. I've tried AJAX with this tutorial and this one but I still don't understand how to pass a variable between js and 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);
};

标签: javascriptnode.jsjson

解决方案


I figured out that if you put your styles and local js into your HTML file you can write that to the screen then take any input from the local js. To give the server data you can

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

Here is my node code that takes the input and writes the screen.

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

Helpful links:How to send JSON dataHow to send dataHandling requests


推荐阅读