REST API NodeJS无法正常工作

时间:2017-01-10 15:39:02

标签: node.js

人。

我休息一下,看看有关AngularJS的前端信息,但是同样的例子几分钟我没有请求,当我返回查询错误时,我必须重新启动节点每次重新运行< / p>

我以npm start REST.js开头我不知道它是否正确。

REST.js

&#13;
&#13;
var mysql = require("mysql");
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var datetime = new Date();

function REST_ROUTER(router,connection,md5) {
    var self = this;
    self.handleRoutes(router,connection,md5);
}

REST_ROUTER.prototype.handleRoutes = function(router,connection,md5) {
    var self = this;
    router.get("/",function(req,res){
        res.json({"Message" : "Hello World !"});
    });

    //Allow CORS conections.
    router.use(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
        next();
    });

    router.get("/users",function(req,res){
        var query = "SELECT * FROM ??";
        var table = ["cuenta"];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json(rows);
            }
        });
    });

    router.get("/admins",function(req,res){
        var query = "SELECT * FROM ?? WHERE adminlvl >= 1";
        var table = ["cuenta"];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json(rows);
            }
        });
    });

    router.get("/login/:name/:password",function(req,res){
        var query = "SELECT * FROM ?? WHERE nombre = ? AND pass = ?";
        var table = ["cuenta", req.params.name, crypto.createHash('md5').update(req.params.password).digest("hex")];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } 
            if (Object.keys(rows).length === 0) {
                res.json({"login" : false, "Message" : "Usuario y/o contraseña incorrectos"});
            }else {
                var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
                res.json({login: true, token: token});
            }
        });
    });

    router.get("/new",function(req,res){
        var query = "SELECT * FROM ?? WHERE ?? LIKE ?";
        var table = ["cuenta", "fecha", "%"+datetime.getFullYear()+"%"];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json({users: rows.length});
            }
        });
    });


    router.get("/names",function(req,res){
        var query = "SELECT nombre FROM ??";
        var table = ["cuenta",];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json(rows);
            }
        });
    });

    router.get("/users/:user_id",function(req,res){
        var query = "SELECT * FROM ?? WHERE ??=?";
        var table = ["cuenta","id",req.params.user_id];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json(rows);
            }
        });
    });
   

   router.get("/users",function(req,res){
        var query = "INSERT INTO ??(??,??) VALUES (?,?)";
        var table = ["cuenta","email","pass",req.body.email,md5(req.body.password)];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                res.json({"Error" : false, "Message" : "User Added !"});
            }
        });
    });


module.exports = REST_ROUTER;
&#13;
&#13;
&#13;

Server.js

&#13;
&#13;
var express = require("express");
var mysql   = require("mysql");
var bodyParser  = require("body-parser");
var md5 = require('MD5');
var rest = require("./REST.js");
var app  = express();

function REST(){
    var self = this;
    self.connectMysql();
};

REST.prototype.connectMysql = function() {
    var self = this;
    var pool      =    mysql.createPool({
        connectionLimit : 1000,
        host     : 'xxxx',
        user     : 'xxxx',
        password : 'xxxx',
        database : 'xxxx',
        debug    :  false
    });
    pool.getConnection(function(err,connection){
        if(err) {
          self.stop(err);
        } else {
          self.configureExpress(connection);
        }
    });
}

REST.prototype.configureExpress = function(connection) {
      var self = this;
      app.use(bodyParser.urlencoded({ extended: true }));
      app.use(bodyParser.json());
      var router = express.Router();
      app.use('/api', router);
      var rest_router = new rest(router,connection,md5);
      self.startServer();
}

REST.prototype.startServer = function() {
      app.listen(80,function(){
          console.log("El servidor esta escuchando el puerto 80.");
      });
}

REST.prototype.stop = function(err) {
    console.log("PROBLEMA CON MYSQL " + err);
    process.exit(1);
}

new REST();
&#13;
&#13;
&#13;

几分钟没有请求后,它返回我设置的错误{&#34;错误&#34;:true,&#34;消息&#34;:&#34;执行MySQL查询错误&#34 ;}

0 个答案:

没有答案