Node.js:单击注册按钮

时间:2018-07-09 14:52:56

标签: javascript mysql node.js express

有一个简单的express.js应用程序,该应用程序必须连接到mysql数据库,然后从用户那里获取信息以在数据库中进行注册。尽管该应用程序正确连接到数据库,但单击注册按钮尚未执行任何操作。这是我的代码

App.js

 var express = require("express");
    var login = require('./routes/register');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(express.static(__dirname + "/static"));
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    var path = require('path');
    //app.set('views', path.join(__dirname, 'static/views'));
    //app.use('/scripts', express.static(path.join(__dirname, 'node_modules')));
    //app.use(express.static(path.join(__dirname, 'static')));
    var engines = require('consolidate');
    app.engine('html', engines.mustache);
    app.set('view engine', 'html');

    var router = express.Router();
    app.get('/',function (req,res) {
        res.sendFile(__dirname + '/static/register.html');
    });
    router.post('/register',register.register);    
    app.use('/api', router);
    app.listen(5000);

register.js

var express    = require("express");
var router     = express.Router();
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'CREBA'
});
connection.connect(function(err){
    if(!err) {
        console.log("Database is connected ... nn");
    } else {
        console.log("Error connecting database ... nn");
    }
});
exports.register = function(req,res){
    // console.log("req",req.body);
    var USER={
        "NAME":req.body.firstname,
        "FAMILY":req.body.lastname,
        "ID":req.body.personaly,
        "POS":req.body.position
    }
    connection.query('INSERT INTO USER SET ?',USER, function (error, results, fields) {
        if (error) {
            console.log("error ocurred",error);
            console.log({
                "code":400,
                "failed":"error ocurred"
            })
        }else{
            console.log('The solution is: ', results);
            console.log({
                "code":200,
                "success":"user registered sucessfully"
            });
        }
    });
}

HTML:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Node Js APP</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/home.css">
    <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>

    <script type="text/javascript" src="js/home.js"></script>
</head>
<body>
<div class="jumbotron">
    <div class="container">
        <h1 id="header">Node JS APP</h1><span id="auth" class="label label-info"> -- </span>

        <div id="authBox">
            <div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%">
                <h3> Login </h3>
                <div> <span>first</span><input class="form-control" id="firstname"> </div>
                <div> <span>last</span> <input class="form-control" id="lastname">  </div>
                <div> <span>last</span> <input class="form-control" id="personaly">  </div>
                <div> <span>last</span> <input class="form-control" id="position">  </div>
                <button style="margin: 5px" class="btn btn-primary" id="register"> register </button>
            </div>
            <div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%" >
                <h3> Sign Up </h3>
                <div><span> Username</span><input class="form-control" id="signUpUser"> </div>
                <div><span> Password </span> <input class="form-control" id="signUpPass"> </div>
                <button style="margin: 5px" class="btn btn-primary" id="signUp"> Sign Up !</button>
            </div>
        </div>
    </div>
</div>
<div class="alert alert-danger" style="text-align: center ; "></div>
<div class="alert alert-success" style="text-align: center ;"></div>
<div style="text-align: center ; border: 1px solid #e2e2e2 ; margin: 20px " id="cmBox">
    <div style="width:75% ; padding: 20px ; margin: auto "><span> Enetr Comment: </span> <input class="form-control" id="msg"> </div>
    <button class="btn btn-success" id="submitComment"> Submit </button>
    <ul id="commentBox" class="list-group" style="margin: 25px 20%">

    </ul>
</div>

home.js

$(document).ready(function () {
    var isAuth = false ;
    var errorBox = $("div.alert-danger") ;
    var successBox = $("div.alert-success") ;
    successBox.slideUp(1);
    errorBox.slideUp(1);
    console.log(successBox);
    $("#register").click(function () {
        console.log({ firstname : $("#firstname").val() ,lastname :  $("#lastname").val() , personaly :  $("#personaly").val() ,POS :  $("#POS").val() }) ;
        $.post("/register" , { username : $("#firstname").val() ,password :  $("#lastname").val ,( "#personaly").val() ,POS :  $("#POS").val() } , function (data) {
            if (data['status']) {
                successBox.slideUp(1);
                errorBox.slideUp(1);
                successBox.html(data['msg']).slideDown(500) ;
                getInfo() ;
            }
            else {
                successBox.slideUp(1);
                errorBox.slideUp(1);
                errorBox.html(data['msg']).slideDown(500) ;
                getInfo() ;
            }
        })
    }) ;

    getInfo() ;


}) ;

1 个答案:

答案 0 :(得分:1)

我怀疑您有404 Not found;)(虽然不确定,但从我的角度来看)。

您的快速应用中的这些行:

router.post('/register',register.register);    
app.use('/api', router);

我已经有一段时间没有使用express了,但是从我的记忆中,这意味着在您的客户端应用程序中,您应该调用/api/register而不是/register

尝试以下操作:在$.post("/api/register" ...文件中home.js

此外,当心:

您在快递服务器中的后处理程序以这种方式读取position参数: req.body.position

但是客户端是通过POS而不是position发送的,因此,位置值在您的服务器中可能始终为undefined