Передача и получение переменной от клиента к серверу JS, HTML, http, node js
Всем привет. Требуется самый простой способ передачи и получение данных между сервером и клиентом. Точнее используется локальный сайт для внутренней сети, шифровка не нужна, нужно просто что бы при нажатие на кнопку в html файле, передавались данные из переменной(по сути передать нужно объект), которая находится в html на сервер. Сервер в данный момент запушен с помощью node js http. При этом выполнить функцию на сервере и передать ответ обратно по запросу уже с сервера опять же с переменной(объектом). Есть ли способ это сделать без php. Ну или если нетрудно написать легкий пример. Создание json отдельного файла не очень удобно для такой задачи.Код я добавил , но он не доделан ещё, но можно понять ход мысли надеюсь)) Надеюсь на вашу помощь, спасибо!
// Код сервера на данный момент.
var infodatebase;
const http = require('http');
const fs = require('fs');
const bcrypt = require(`bcrypt`);
const saltRounds = 10;
const css = fs.readFileSync('style.css');
const js = fs.readFileSync('script.js');
const html_main = fs.readFileSync('index.html');
const mysql = require('mysql'); // подключаем библиотеку к скрипту
const pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : '-',
password : '-',
database : '-'
});
pool.getConnection(function(err, connection) { // подключаемся
if (err) { // в случае ошибки в err будет объект ошибки
console.error('[MySQL] Ошибка подключения: ' + err.stack);
return;
}
loadingsql();
console.log('[MySQL] Успешное подключение к базе данных');
});
function loadingsql() {
pool.query('SELECT id, name, year, number, date FROM statistikwork', function (err, results){
infodatebase = results;
//console.log(infodatebase);
});
};
http.createServer((req, res) => {
switch (req.url) {
case '/':
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html_main);
return;
case '/style.css':
res.writeHead(200, { 'Content-Type': 'text/css' });
res.end(css);
return;
case '/script.js':
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(js);
return;
default:
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404 Не найдено');
return;
}
}).listen(3000, () => console.log('Сервер работает'));
function testway() {
console.log(`Успех`);
}
// Клиент:
var list = document.getElementById('name'),
arr1 = [
"объект 1",
"объект 2",
"объект 3"
],
item = document.createElement('option');
for (var i = 0; i < arr1.length; i++)
{
item.innerHTML = arr1[i];
list.appendChild(item.cloneNode(true));
}
//
var list = document.getElementById('operation'),
arr2 = [
"ЗАКРЫТ",
"ВСКРЫТ",
],
item = document.createElement('option');
for (var i = 0; i < arr2.length; i++)
{
item.innerHTML = arr2[i];
list.appendChild(item.cloneNode(true));
}
//
var list = document.getElementById('worker'),
arr = [
"фамилия 1",
"фамилия 2",
"фамилия 3",
"фамилия 4",
"фамилия 5",
"фамилия 6",
],
item = document.createElement('option');
for (var i = 0; i < arr.length; i++)
{
item.innerHTML = arr[i];
list.appendChild(item.cloneNode(true));
}
//
var date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1) > 9 ? "" + (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
let test = date.getDate();
let TimeReal = `${test}.${month}.${year}`;
document.getElementById("date").value = TimeReal;
//
var list = document.getElementById('searth'),
arr4 = [
"0",
"1",
"2",
],
item = document.createElement('option');
for (var i = 0; i < arr4.length; i++)
{
item.innerHTML = arr4[i];
list.appendChild(item.cloneNode(true));
}
let newobject = {};
function trysave() {
if(document.getElementById("naumenovanie").value && document.getElementById("numbermodyla").value && document.getElementById('worker') && document.getElementById('operatia'))
{
newobject = {
name: document.getElementById(`naumenovanie`).value,
year: document.getElementById(`godmodyla`).value,
number: document.getElementById(`numbermodyla`).value,
operation: document.getElementById(`operatia`).value,
information: document.getElementById(`dopoperatia`).value,
executor: document.getElementById(`icpolnitel`).value,
date: document.getElementById(`date`).value,
status: `Непроверен`,
finalinformation: ``,
conclusion: ``,
finalexecutor: ``
}
//alert(`${JSON.stringify(newobject)}`);
}
else {
alert(`Заполните основные поля!`);
}
};
Ответы (1 шт):
Я нашёл решение, записал папку views в resource через package.json
"extraResources": ["views"]
Далее в папку с основным кодом указал пути к файлам и папке:
appp.set('views', './resources/views'); соответственно: res.render('index.ejs');
res.sendFile('style.css', { root: path.join(__dirname, '../views') });
res.sendFile('script.js', { root: path.join(__dirname, '../views') });