调用app.use / app.post(将其插入数据库)以获取表单值

时间:2019-02-14 17:08:17

标签: javascript jquery node.js express

我创建了一个带有express的app.use以便将值插入数据库中。我想在用户点击注册时获得这些值。

我的表单:

<form class="form-signin" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="inputEmail" id="lblEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email 
address" name="email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" 
placeholder="Password" name="passworf" required>
<label for="repeatInputPassword" class="sr-only">Repeat Password</label>
<input type="password" id="repeatinputPassword" class="form-control" 
placeholder="Repeat Password" required>
<label for="name" class="sr-only">Name</label>
<input type="name" id="inputName" class="form-control" placeholder="Name" 
name="name" required>
<label for="surname" class="sr-only">Surname</label>
<input type="surname" id="inputSurname" class="form-control" 
placeholder="Surname" name="surname" required>
<div class="checkbox mb-3">
</div>
<button class="btn btn-lg btn-primary btnblock-" 
type="submit">Register</button>
<p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p>
</form>

app.use用于在数据库中插入值。我在下面使用MySQL:

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var http = require('http');
var urlencodedParser = bodyParser.urlencoded({extended: false});

app.use('/', urlencodedParser, function(req,res, next){
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
console.log(req.body);
var sql = "INSERT INTO admins VALUES(null, ?, ?, ?, ?) ";
con.query(sql, [ adminUser, adminPass, adminName, adminSurname], 
  function(error, rows, fields){
    if(!!error) {
        console.log('Query Failed' + error.message);
    } else {
        console.log('Query Successful');
        console.log(rows.insertId);
        next();
    }
  });
 })

app.listen(5500);

2 个答案:

答案 0 :(得分:-1)

您的表单必须将POST请求发送到您用app.use(...)定义的相同路由。在这种情况下,您的表单将POST设置为与之相同的路径,这意味着它必须在/路径上才能工作。

将您的app.use(...)更改为app.post(...),使其仅处理POST请求,然后使用以下方法从同一路由提供表单的html:

app.get('/', function(req, res) {
  res.sendFile(path-to-form);
})

请参阅:https://codesandbox.io/s/won9jzj8k7

答案 1 :(得分:-1)

您需要创建一个Express POST route表单也可以发布。

app.post('/', function (req, res) {
  // Process form here
  var adminUser = req.body.email;
  var adminPass = req.body.password;
  var adminName = req.body.name;
  var adminSurname = req.body.surname;
  // etc.
});

路径应与表单action属性匹配