javascript - 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);
};
解决方案
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
推荐阅读
- kotlin - Kotlin 协程未在 main 上运行启动
- nuget - 安装nuget时需要打开一个readme.md文件
- django - 使用具有多个 PK 的 URL 处理重定向
- javascript - 防止或处理同一部分中子标签和父标签的点击事件
- android - ViewModel 观察运行多次,以获取 API 的单次命中
- asp.net-core - jwt 刷新令牌而不保存任何地方
- mongodb - 我们如何获得所有周期时间超过几分钟的文档
- javascript - 如何查找所有行并获取续集中所有行的总和
- laravel - 如何获取 laravel 项目中的会话数?
- ios - VC加载时如何默认打开特定选项卡,在CAPSPageMenu中打开子ViewController时如何移动到索引选项卡?