如何使用NODE.JS将表单结果上传到MYSQL



我非常感谢您的帮助!在EJS文件中,我有一个partials/test,它包含一个多步骤形式;js";。在多步骤形式中,用户添加一些由js文件中的函数计算的数据。这些功能为用户提供了一个";结果";在表单的最后一页。我需要将结果添加到MYSQL中。

我尝试了不同的方法来做到这一点:

  • 由于我需要上传到MYSQL的不是表单的输入,而是基于这些输入的计算结果,我认为方法:POST+提交按钮不起作用(我无论如何都试过了,但没有成功(。

  • 我试图使用document.getElementById((.inerHTML访问包含多步骤最后一页中计算结果的

    元素,然后将其保存到对象或变量中,并将该对象上传到MYSQL,但没有成功。当我试图将数据库连接导入verification.js文件时,我收到一个错误,说";不能在模块外使用导入;。如果我将verification.js文件更改为type=module而不是text/javascript,那么我在该文件上的函数将停止工作。所以我不能更改脚本的类型。(仅供参考,我在PackageJson中已经有type=模块(

  • 我还尝试在EJS文件中执行内联脚本,在那里添加计算函数,并将JS脚本的类型更改为模块,这样我就可以导入数据库连接,但在导入之后,我收到了404代码错误,说它找不到连接所在的数据库文件。因此,作为一种变通方法,我尝试编写整个连接代码,以便不从另一个文件导入数据库连接,从从'mysql'导入mysql开始,但在这样做之后,我得到了另一个错误,即";未能解析模块说明符";mysql";。相对引用必须以"或"开头/&"&"/&";,或"/&";。

我不知道还能做什么……如果有人能帮我,我真的很感激如何将此表单结果上传到MYSQL

index.js

import express from "express";
import {dirname, join} from 'path'
import { fileURLToPath } from "url"
import rutas from './routes/index.js'
import morgan from 'morgan'
import session from "express-session";
import MySQLStore from "express-mysql-session";
import path from 'path';
import passport from "passport";
import flash from "connect-flash";
import localStrategy from "./lib/passport.js";
const app = express()
const __dirname = dirname(fileURLToPath(import.meta.url))
app.set('view engine', 'ejs')
app.set('views', join(__dirname, 'views')) 
app.use(express.static(join(__dirname, 'public'))) 
//MIDDLEWARES
app.use(session({ 
secret: 'alissarobot', 
resave: false, 
saveUninitialized: false, 
store: new MySQLStore({host: 'localhost',
hostname: '127.0.0.1',
database: 'alissa',
user: 'root',
password: 'AEHLAEHL19961996'}) })); 
app.use(flash());
app.use(express.urlencoded({extended: true}));
app.use(express.json()) 
app.use(passport.initialize()); 
app.use(passport.session());
//GLOBAL VARIABLES
app.use((req, res, next) => {
app.locals.message = req.flash('message');
app.locals.success = req.flash('success');
app.locals.user = req.user;
next();
})
//ROUTES
app.use(rutas)
app.use(morgan('dev'));
app.listen(8000)
console.log('Server is listening on port', 8000);

alissa.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ALISSA</title>
<link rel="stylesheet" href="/css/profile.css">
<link rel="stylesheet" href="/css/alissa.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<link rel="stylesheet" 
<%- include('partials/head') %>
</head>
<body style="background-color: #f5f6f5" ;>
<%- include('partials/navigation') %>
<%- include('partials/test') %>
<div>
<div class="wave"></div>
<div class="wave"></div>
<div class="wave"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script type="text/javascript" src="./verificationtrade.js"></script>
</body>
</html>

database.js

import mysql from 'mysql';
import { createPool } from 'mysql';
import { promisify } from 'util';
const pool = mysql.createPool({
host: 'localhost',
hostname: '127.0.0.1',
database: 'alissa',
user: 'root',
password: 'AEHLAEHL19961996'
});

pool.getConnection((err, connection) => {
if (err) {  console.log(err)  }
if (connection) connection.release();
console.log('DB IS CONNECTED');
return;
});
pool.query = promisify(pool.query); //para convertir callbacks en promesas
export default pool;

test.ejs

<div class="container">
<form id="msform" action="/alissa" method="POST">
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Hora</li>
<li>Ciclo</li>
<li>Precio</li>
<li>Peaks</li>
<li>Ciclo</li>
<li>Precio</li>
<li>Peaks</li>
</ul>
<!-- fieldsets -->
<fieldset>

<h3 class="mt-3 mb-4" style="color: white; font-family: Raleway;">Nueva operación</h3>
<h3 class="fs-subtitle mt-1 mb-3" style="color: white; font-size: 14px; ">Selecciona la divisa</h3>
<select id="list" onchange="getSelectedValue(); "
class="btn btn-light iniciar dropdown-toggle mb-4 mt-3 pl-3 pr-3" type="button "
data-bs-toggle="dropdown" aria-expanded="false" style="padding: 5px;" name="parpar">
<option value="Divisa">Divisa</option>
<option value="EurUsd">EurUsd</option>
<option value="GbpUsd">GbpUsd</option>
<option value="UsdChf">UsdChf</option>       
</select>
<br>          
<input type="button" name="next" class="btn btn-primary next action-button mt-4" value="Continuar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<h3 class="mt-3 mb-4" style="color: white; font-family: Raleway;">Tiempo</h3>
<h3 class="fs-subtitle mt-1 mb-3" style="color: white; font-size: 14px;">Ingresa la hora actual</h3>
<select id="datehour" onchange="getSelectedHour(); "
class="btn btn-light iniciar dropdown-toggle mb-4 pl-3 pr-3 text-center" type="button number"
data-bs-toggle="dropdown" aria-expanded="false" style="padding: 5px; padding-bottom: 7px;" >
<option style="text-align: center" value="">Hora</option>
<option style="text-align: center" value="1">1</option>
<option style="text-align: center" value="2">2</option>
<option style="text-align: center" value="3">3</option>
<option style="text-align: center" value="4">4</option>
<option style="text-align: center" value="5">5</option>
<option style="text-align: center" value="6">6</option>
<option style="text-align: center" value="7">7</option>
<option style="text-align: center" value="8">8</option>
<option style="text-align: center" value="9">9</option>
<option style="text-align: center" value="10">10</option>
<option style="text-align: center" value="11">11</option>
<option style="text-align: center" value="12">12</option>
<option style="text-align: center" value="13">13</option>
<option style="text-align: center" value="14">14</option>
<option style="text-align: center" value="15">15</option>
<option style="text-align: center" value="16">16</option>
<option style="text-align: center" value="17">17</option>
<option style="text-align: center" value="18">18</option>
<option style="text-align: center" value="19">19</option>
<option style="text-align: center" value="20">20</option>
<option style="text-align: center" value="21">21</option>
<option style="text-align: center" value="22">22</option>
<option style="text-align: center" value="23">23</option>
<option style="text-align: center" value="24">24</option>
</select>
<select id="dateminutes" onchange="getSelectedMinutes(); "
class="btn btn-light iniciar dropdown-toggle mb-4 pl-3 pr-3 text-center" type="button number"
data-bs-toggle="dropdown" aria-expanded="false" style="padding: 5px; padding-bottom: 7px;" >
<option style="text-align: center" value="">Minutos</option>
<option style="text-align: center" value="00">00</option>
<option style="text-align: center" value="05">05</option>
<option style="text-align: center" value="10">10</option>
<option style="text-align: center" value="15">15</option>
<option style="text-align: center" value="20">20</option>
<option style="text-align: center" value="25">25</option>
<option style="text-align: center" value="30">30</option>
<option style="text-align: center" value="35">35</option>
<option style="text-align: center" value="40">40</option>
<option style="text-align: center" value="45">45</option>
<option style="text-align: center" value="50">50</option>
<option style="text-align: center" value="55">55</option>
</select>
<br>
<h3 class="fs-subtitle mt-1 mb-3" style="color: white; font-size: 14px;">¿Qué día es hoy?</h3>
<select id="day" onchange="getSelectedDay();"
class="btn btn-light iniciar dropdown-toggle mb-4 pl-3 pr-3 text-center" type="button "
data-bs-toggle="dropdown" aria-expanded="false" style="padding: 5px; padding-bottom: 7px;">
<option style="text-align: center" value="">Día</option>
<option style="text-align: center" value="Lunes">Lunes</option>
<option style="text-align: center" value="Martes">Martes</option>
<option style="text-align: center" value="Miercoles">Miercoles</option>
<option style="text-align: center" value="Jueves">Jueves</option>
<option style="text-align: center" value="Viernes">Viernes</option>
</select>
<br>
<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input type="button" name="next" class="btn btn-primary next action-button mt-4" value="Continuar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<h3 class="mt-3 mb-4" style="color: white; font-family: Raleway;">Precio actual</h3>
<h3 class="fs-subtitle mt-1 mb-3" style="color: white; font-family: Raleway; font-size: 14px;">Ingresa el punto en el que se
encuentra el
mercado en tu divisa en este momento</h3>
<input onchange="getSelectedPrice();" id="price" type="number"  placeholder="Precio actual" class="mb-4"/> 

<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input type="button" name="next" class="btn btn-primary next action-button mt-4" value="Continuar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<h3 class="mt-3 mb-4" style="color: white; font-family: Raleway;">6pm - 12:30am</h3>
<h3 class="fs-subtitle mt-1 mb-3" style="color: white; font-family: Raleway; font-size: larger; font-size: 14px;">Ingresa el punto máximo (más
alto) y el punto
mínimo (más bajo) al que llegó el mercado en tu divisa durante esas horas</h3>
<input onchange="getAsiaMaxPrice();" id="asiamaxprice" type="int" name="fname"
placeholder="Precio máximo" />
<input onchange="getAsiaMinPrice();" id="asiaminprice" type="int" name="lname"
placeholder="Precio mínimo" class="mb-4"/>
<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input  type="button" id="" onclick="newTrade2();newTrade3(); newOperation();  newTrade4(); newTrade5(); newTrade6(); newTrade7(); newTrade8(); tradingzonesell(); notradingzoneyet(); asiarange(); greattrade(); notradingzoneyetforbuy(); badhourtrading(); goodtradebuy(); greattradebuy(); newTrade9(); below1hour(); " 

class="btn next action-button btn-primary mt-4" value="Enviar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<h5 style="color: white" class=" text-center">Ayer</h5>
<p style="font-family: Raleway; color: white;">Ingresa el punto máximo (más alto) y el punto
mínimo (más bajo) al que llegó el mercado en tu divisa ayer
</p>
<input  onchange="getMaxAyer()" id="maximoayer" type="int" name="fname" placeholder="Precio máximo" autofocus style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>
<input onchange="getMinAyer()" id="minimoayer"  type="int" name="lname" placeholder="Precio mínimo" style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>

<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input type="button" name="next" class="btn btn-primary next action-button mt-4" value="Continuar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<h5 style="color: white" class=" text-center">Anteayer</h5>
<p style="font-family: Raleway; color: white;">Ingresa el punto máximo (más alto) y el punto
mínimo (más bajo) al que llegó el mercado en tu divisa anteayer
</p>
<input id="maximoanteayer" onchange="getMaxAnteayer()"  type="int" name="fname" placeholder="Precio máximo" autofocus style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>
<input id="minimoanteayer"  onchange="getMinAnteayer()" type="int" name="lname" placeholder="Precio mínimo" style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>

<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input type="button" name="next" class="btn btn-primary next action-button mt-4" value="Continuar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>

<h5 style="color: white" class=" text-center">Hace 3 días</h5>
<p style="font-family: Raleway; color: white;">Ingresa el punto máximo (más alto) y el punto
mínimo (más bajo) al que llegó el mercado en tu divisa hace 3 días
</p>
<input onchange="getMaxTdias()" id="maximo3dias" type="int" name="fname" placeholder="Precio máximo" autofocus style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>
<input onchange="getMinTdias()" id="minimo3dias" type="int" name="fname" placeholder="Precio mínimo" style="color: black; font-family: Raleway; font-size: larger; font-size: 14px;"/>

<input type="button" name="previous" class="btn btn-primary previous action-button mt-4" value="Previous"
style="color: white; font-weight: bolder;" />
<input  type="button" id="" onclick="uptrend(); downtrend(); stophuntsell(); stophuntbuy(); consolidacion();  alcista(); bajista(); posiblestophuntbajista();  posiblestophuntalcista(); tiempoconsolidacion(); status(); status1(); status2(); status3();  " 

class="btn next action-button btn-primary mt-4" value="Enviar"
style="color: white; font-weight: bolder;" />
</fieldset>
<fieldset>
<img style="border-radius: 50px" src="https://thumbs.dreamstime.com/b/blonde-icon-flat-style-white-background-woman-symbol-stock-vector-illustration-79131143.jpg" height="50" width="50" />           
<h5 style="color: white" class=" text-center mt-2">¡Hora de hacer  trading!</h5>
<p style="font-family: Raleway; color: white; background-color: green; border-radius: 5px; font-size: 20px;" class="mt-4 pl-3 pr-3" id="tradeorientation" name="tipo"  >Compra</p>
<br>
<p style="font-family: Raleway; color: white;">Calidad del trade: <span
style="font-weight: bold; color: white;" id="calidadtrade" name="ctrade">Buena</span> </p>
<p style="font-family: Raleway; color: white;">Take Profit:<span style="font-weight: bold" id="takeprofit" name="tomaganancia">1.256</span></p>
<p style="font-family: Raleway; color: white;" class="mb-1">Stop Loss: <span style="font-weight: bold" id="stoploss" name="tomaperdida">1.153</span></p>
<br>
<p class="mt-4" style="font-family: Raleway; color: white;" id="comment">Si la operación no está en ganancia en 3 horas ciérrala</p>
<a href="/profile"><input type=" button" onclick="build();" class="btn btn-primary mt-4" value="Listo" style="color: white; font-weight: bolder;" /></a>
</fieldset>
</form>
</div>

您似乎对哪个JavaScript程序可以做什么感到困惑。

您有三个程序(都是用JS编写的,但都是不同的(。

  1. 您的HTTP服务器(使用Express和Node.js(。它负责侦听HTTP请求并向浏览器发送响应。它还负责你想对浏览器发送给你的数据做的任何事情
  2. 您的EJS程序。这是在服务器上运行的,但应该被视为独立的。它是像<%%>这样的标签之间的JS。它负责获取1传递给它的数据,并将其转换为HTML(此时它将HTML文档传递回1以发送到浏览器(
  3. 您的<script>元素。它们在浏览器上运行,负责处理您想要处理的数据,并在不返回服务器的情况下更新浏览器中的DOM

与数据库的任何交互都应由1(HTTP服务器(完成。使用2(模板(是没有意义的,使用3不能(客户端代码(。

如果您正在客户端上运行计算(使用3(,并希望将结果放入数据库中,那么您的选项是:

  • 使用表单将用户输入的数据提交到服务器。在服务器上重新进行计算
  • 提交客户端JS使用表单生成的数据。这将涉及使用客户端JavaScript生成或更新input元素(例如<input type="hidden" ...>(,然后提交表单
  • 提交客户端JS使用Ajax(通常使用Fetch API(生成的数据。这使您可以在不离开用户当前正在查看的页面的情况下发送数据

最新更新