使用Nodejs + Express登录和注册,用户数据未定义

时间:2019-07-14 14:17:27

标签: javascript mysql node.js express

我有一个简单的注册页面,该页面应将用户输入的信息(姓名,电子邮件,密码)存储在数据库中。我正在使用express和node。我想尝试的事情是将所有数据库操作(插入,选择等)都注册到一个文件中,然后将响应从另一个文件发送到服务器。

dbQuery.js

var express=require("express");
var app = express();
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'user_name',
  password : 'password',
  database : 'database'
});
connection.connect(function(err){
if(!err) {
    console.log("Database is connected");
} else {
    console.log("Error while connecting with database");
}
});

 module.exports.register=function(callback){
 app.get('/register',function(req,res){
  var today = new Date();
    var users={
        "name":req.body.name,
        "email":req.body.email,
        "password":req.body.password,
        "created_at":today,
        "updated_at":today
    }
      return connection.query('INSERT INTO users SET ?',users, callback) 
}
}

app.js

var express=require("express");
var connection = require('./dbQuery');
var app = express();
app.post('/register',function(req,res){
  connection.register(function(error, results, fields){
   if (error) {
        res.json({
            status:false,
            message:'there are some error with query for registration'
        })
      }else{
        console.log('is it coming here in else')
          res.json({
            status:true,
            data:results,
            message:'user registered sucessfully'
        })
      }
    })
})

index.html

<html>  
    <body>  
        <form action="/register" method="POST">  
            First Name: <input type="text" name="name">  

            Email: <input type="text" name="email">
            Password: <input type="password" name="password">

            <input type="submit" value="Submit">  
        </form>
    </body>  
</html> 

当我执行app.js时,服务器只会继续加载而不会提供任何东西

我希望输出应该在服务器上显示json响应,即“用户成功注册”,但是它会继续加载。

2 个答案:

答案 0 :(得分:0)

尝试将dbQuery.js更改为此:

var mysql = require("mysql");
var connection = mysql.createConnection({
  host: "localhost",
  user: "user_name",
  password: "password",
  database: "database"
});
connection.connect(function(err) {
  if (!err) {
    console.log("Database is connected");
  } else {
    console.log("Error while connecting with database");
  }
});

module.exports.register = function(callback) {
  var today = new Date();
  var users = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    created_at: today,
    updated_at: today
  };
  connection.query("INSERT INTO users SET ?", users, callback);
};

答案 1 :(得分:0)

您做错了,如果在这里通过快递发布API的简单步骤

您的app.js文件应为

  var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    const i18n = require("i18n");
    var indexRouter = require('./routes/index');
// this is the api file created under the routes folder 
    var apiRouter = require('./routes/api');
    require('./database')

    var app = express();

    app.use(i18n.init);

    i18n.configure({
      locales: ['en', 'de'],
      cookie: 'LocalLang',
      defaultLocale: 'en',
      extension: ".json",
      directory: __dirname + '/locales',
      register: global,
      logDebugFn: function (msg) {
        console.log('debug', msg);
      },
      logWarnFn: function (msg) {
        console.log('warn', msg);
      },
      logErrorFn: function (msg) {
        console.log('error', msg);
      }
    });
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    app.use('/', indexRouter);
    app.use('/api', apiRouter);

    // catch 404 and forward to error handler
    app.use(function (req, res, next) {
      next(createError(404));
    });

    // error handler
    app.use(function (err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('pages/error');
    });

    module.exports = app;

在app.js文件中需要的api.js文件中

var express = require('express');
var router = express.Router();
//Import your query.js file 
const query = require('path for the file ./query')

router.post('/register',query.register)

module.exports = router;

query.js文件应类似于

 var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'user_name',
      password : 'password',
      database : 'database'
    });
    connection.connect(function(err){
    if(!err) {
        console.log("Database is connected");
    } else {
        console.log("Error while connecting with database");
    }
    });
    exports.register = (req, res)=>{
    var today = new Date();
      var users = {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        created_at: today,
        updated_at: today
      };
      connection.query("INSERT INTO users SET ?", users, (error,result)=>{
    if(err)
     return res.send({status:false, message:"Error in savind data in db"})

    return res.send({status:true, message:"Resgistered sucessfully"})
  });
 }