javascript 使用带有 Express 的 nodejs 将表单数据发布到 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45891998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:18:31  来源:igfitidea点击:

Posting Form data to MySQL using nodejs w/ Express

javascriptmysqlnode.jsexpress

提问by snikt

I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I will post the code and error below. I'm struggling to resolve this issue.

我正在尝试在 Node 中编写一个简单的 server.js,它将表单数据从我的 html 文件发布到 MySQL。但我收到语法错误。我将在下面发布代码和错误。我正在努力解决这个问题。

<head>

    <title>Learning Node Server</title>
    <link rel="stylesheet" href="style.css" />

</head>


<body>

    <div class="header">
        <h1>Learning Node and JS</h1>
        <p>With Ninad</p>       
    </div>

    <form action="/data" method="post">
        <label for="name">Enter your name in the database</label>
        <input type="text" name="name">
        <input type="submit" value="submit" />
        </form>


    <div class="container"></div>

    <script type="text/javascript" src="main.js"></script>

</body>

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



app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//app.use(express.json());
//app.use(express.urlencoded());
//app.use(app.router);
app.use(express.static('public'));


var connection = mysql.createConnection({

  host     : 'localhost',
  user     : 'root',
  password : '3748',
  database : 'nodedb'

});

connection.connect();


app.get('/', function (req, res) {

    res.sendFile(__dirname + '/node.html');

});


app.post('/data', function(req, res){

    var username=req.body.name;

    connection.query("INSERT INTO `names` (name) SET ?", username.toString(), function(err, result){
        if(err) throw err;

        console.log("1 record inserted");
    });

    res.send(username);

});

//connection.end();

app.listen(3000, function () {
console.log('Example app listening on port 3000');
});

If I entered yahoo2 as the name, this is the error I get-

如果我输入 yahoo2 作为名称,这就是我得到的错误-

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET 'yahoo2'' at line 1 at Query.Sequence._packetToError (/home/ninad/node-workspace/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)

你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 Query.Sequence._packetToError (/home/ninad/node-workspace/node_modules/mysql/lib/protocol/序列/Sequence.js:52:14)

回答by Nicholas

It should be this,

应该是这个

app.post('/data', function(req, res){
    var username=req.body.name;
    connection.query("INSERT INTO `names` (name) VALUES (?)", username.toString(), function(err, result){
        if(err) throw err;
            console.log("1 record inserted");
        });
    res.send(username);
});

回答by Syed Ayesha Bebe

Try this code. Create a views folder and place this jade file in it. This is my jade file I named it as

试试这个代码。创建一个 views 文件夹并将这个 jade 文件放入其中。这是我命名的玉文件

//index.jade

<html>
<head>
<title> test </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="/submit" method="POST">
<fieldset>
<label for="name">Name: </label>
<input type="text" id="name" name="name" />
<br/>
<label for="email">Email: </label>
<input type="email" id="email" name="email"  />
<br/>
<label for="description">Description: </label>
<textarea id="description" name="description"></textarea>
<br/>
<input type="submit" value="create profile" />
</fieldset>
</form>
</body>
</html>

This is my server code save it as index.js

这是我的服务器代码,另存为 index.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var jade = require('jade');
var con = mysql.createConnection({
     host: "localhost",
     user: "root",
     password: "",
     database: "test"
});
var app=express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.set('view engine', 'jade');
app.get('/submit',function(req,res){
res.render('index');
});
app.post('/submit',urlencodedParser, function(req, res, next) {
    console.log(req.body.name);
    console.log(req.body.email);
    console.log(req.body.description);
    con.connect(function(err) {
  if (err) throw  err;
  console.log("connected");
  var sql = "INSERT INTO `form`(`name`,`email`, `description`) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.description+"')";
  con.query(sql, function(err, result)  {
   if(err) throw err;
   console.log("table created");
  });
});

  res.render('index', { title: 'Express' });
});
app.listen(3000,function(){
    console.log("Sever listening on port 3000");
});

Before running the server create a database here I created my database with the name test. And next create a table in it. Here I created a table with the name form.Run the node server as node index.js. And in browser type http://localhost:3000/submit. And next look at the database.Hope this helps...

在运行服务器之前,在这里创建一个数据库,我用名称创建了我的数据库test。然后在其中创建一个表。在这里,我创建了一个名为 form.Run the node server as 的表node index.js。并在浏览器中输入http://localhost:3000/submit. 接下来看看数据库。希望这有帮助......