【问题标题】:HTML form to POST data to MySQL将数据发布到 MySQL 的 HTML 表单
【发布时间】:2015-06-04 23:01:50
【问题描述】:

我正在尝试使用 Node.js 将数据发布到 MySQL 数据库。

这是我的 htmlHTML 表单:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>form</title>
</head>
<body>
<h1>This is my form</h1>
<!-- local host to be changed?  -->
<form action="http://localhost:3000/index.html" method="POST">
    First name:<br>
    <input type="text" name="firstname" value="John">
    <br>
    Last name:<br>
    <input type="text" name="lastname" value="Doe">
    <br><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

这是我的MySQL.js

var mysql = require('mysql');

var connection = mysql.createConnection(
    {
      host     : 'mysqlhost',
      port     : '3306',
      user     : 'myuser',
      password : 'mypassword',
      database : 'myuser'
    } ); connection.connect(); var query = connection.query('SELECT * FROM http://localhost:3000/index.html');

query.on('error', function(err) {
    throw err; });

query.on('fields', function(fields) {
    console.log(fields); })

query.on('result', function(row) {
    console.log(row); }); connection.end();

这可能吗?

【问题讨论】:

  • SELECT * FROM http://localhost:3000/index.html?

标签: javascript html mysql node.js


【解决方案1】:

是的,这是可能的,但你肯定没有朝着正确的方向前进。我建议学习如何制作一个简单的 REST API 节点应用程序以开始使用。这个tutorial 是一个很好的起点。我建议使用 Express,因为它简化了处理 POST/GET 请求的任务。

这里是你想要的启动代码。

index.html

注意我是如何在&lt;form action=...&gt; 部分使用/data 而不是localhost:3000/index.html。这通常称为 REST api。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>form</title>
</head>
<body>
<h1>This is my form</h1>
<!-- local host to be changed?  -->
<form action="/data" method="POST">
    First name:<br>
    <input type="text" name="firstname" value="John">
    <br>
    Last name:<br>
    <input type="text" name="lastname" value="Doe">
    <br><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

app.js

var app = require('express')();
var bodyParser = require('body-parser');
var path = require('path');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/data', function(req, res) {
    console.log(req.body.firstname);
    console.log(req.body.lastname);
    // Add these values to your MySQL database here
});

app.listen(3000);

文件结构

app.js
index.html

要运行的命令

npm install express
npm install body-parser
node app.js

然后只需在浏览器中转到localhost:3000

【讨论】:

  • 谢谢基思!将查看教程并了解有关 express 的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2016-10-22
  • 1970-01-01
  • 2018-05-14
相关资源
最近更新 更多