使用nodejs进行开发并发送表单提交的发布请求时,第一个请求会引发服务器错误500,但后续单击按钮可以正常工作。以下是我的代码。我做错了什么?
的Ajax
$(document).ready(function (e) {
$("#group_ledger_form").on('submit',(function(e) {
e.preventDefault();
var data = {};
data.group_ledger_name = $('#group_ledger_name').val();
data.group_ledger_type = $('#group_ledger_type').val();
$('#loading').show();
$.ajax({
url: "/group-ledger",
type: "POST",
data: data,
dataType: 'json',
cache: false,
processData:true,
success: function(data)
{
if( data.status == '500' ) {
console.log('error occured');
} else {
$('#loading').hide();
}
}
});
}));
});
group_ledger.js
var express = require('express');
var router = express.Router();
var db = require('./../db');
var chart_func = require('./../chart-of-accounts');
router.post('/', function(req, res, next) {
var group_ledger_name = req.body.group_ledger_name;
var group_ledger_type = req.body.group_ledger_type;
chart_func.allChartsByAccountName(group_ledger_name).then(function(pre_rows){
for (var i = 0; i < pre_rows.length; i++) {
pre_account_name = pre_rows[i]['account_name'];
}
});
console.log(pre_account_name);
});
module.exports = router;
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 mysql = require('mysql');
var db = require('./db');
var routes = require('./routes/index');
var chart_of_accounts = require('./routes/chart_of_accounts');
var group_ledger = require('./routes/group_ledger');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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.use('/chart-of-accounts', chart_of_accounts);
app.use('/group-ledger', group_ledger);
// 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;