简体   繁体   中英

NodeJS function does not return response on ajax call

I have a database file called db.js, I'm exporting it to my route and running a query. The code has a callback function to wait for the ajax response. When I run it never ends the ajax call keeps running forever.

Any one know why and how to fix this please?

Thanks

db.js file

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;

app.js

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;

my view code :

$.ajax({
    cache: false,
    type: 'POST',
    data: JSON.stringify(assignmentsOBJ),
    contentType: 'application/json',
    url: '/assign',                     
    beforeSend: function() {
        dialogRef.getModalBody().html('Request processing, please wait...');
    },
    success: function(data) {
        dialogRef.close();
        var response = JSON.parse(data);
        if(response.status === "OK") {
            fncShowDialog(response.message, BootstrapDialog.TYPE_SUCCESS, response.title, response.refresh);    
        }
        else if(response.status === "KO") {
            fncShowDialog(response.message, BootstrapDialog.TYPE_ERROR, response.title, response.refresh);      
        }
    },
    error: function() {
        dialogRef.close();
        fncShowDialog("An error occured! Try later please.", BootstrapDialog.TYPE_ERROR, "Error", false);
    },
    complete: function() {
        dialogRef.close();
    }
});

This line app.use('/', routes); overwride your next route app.post('/assign', function(req, res){}) when you request to '/assign' express app search handler in your router (./routes/index). Delete router or call after '/assign'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM