NodeJS函数不会在ajax调用上返回响应

时间:2016-06-15 05:52:03

标签: javascript ajax node.js

我有一个名为db.js的数据库文件,我将其导出到我的路由并运行查询。代码有一个回调函数来等待ajax响应。当我运行它时,永远不会结束ajax调用永远运行。

任何人都知道为什么以及如何解决这个问题?

由于

db.js文件

<div class="error">Login failed </a>

url: 'myurl',
            type: 'POST',
            data: JSON.stringify(Login),
            contentType: "application/json",

app.js

var mysql = require('mysql');
    var pool = mysql.createPool({
        connectionLimit : 100,//To update with the max of allowed connection after that the new connections are made in the queue
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'nodejs',
        debug    :  false
    });
    function handle_database(query, return_data, callback) {
    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            callback(null, false);
        }      
        connection.query(query,function(err,rows){
            connection.release();
            if(!err) {
                if(return_data){
                    callback(null, JSON.stringify(rows));
                }
            }else{
                callback(null, false);
            }          
        });
        connection.on('error', function() {    
            callback(null, false);    
        });
    });
}
module.exports = handle_database;

我的观看代码:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

app.post('/assign', function(req, res){ 
    var query = "INSERT INTO assigned_stops (jsons) VALUES ('"+JSON.stringify(req.body)+"')";
        handle_database(query, false, function(err, response){
            var obj = {};
            console.log(response);
            if(response !== false){
                obj['status'] = "OK";
                obj['message'] = "Data successfully assigned.";
                obj['title'] = "Success";
                obj['refresh'] = true;
                res.send(JSON.stringify(obj)); 
            }else if(response === false){
                obj['status'] = "KO";
                obj['message'] = "An error occured! Try later please.";
                obj['title'] = "Error";
                obj['refresh'] = false;
                res.send(JSON.stringify(obj));
            }
        });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

1 个答案:

答案 0 :(得分:1)

当您在路由器(./routes/index)中请求'/ assign'快速应用搜索处理程序时,此行app.use('/', routes);会覆盖您的下一个路由app.post('/assign', function(req, res){})。删除路由器或在'/ assign'

后调用