NodeJS没有响应AJAX帖子

时间:2016-03-22 07:06:20

标签: jquery ajax node.js express routes

我'我在客户端使用NodeJS / Express和jquery。在客户端,我不想将json对象发送到NodeJS / Express服务器以进行进一步处理。但相反,我在节点的日志记录中得到以下消息:

POST /BusinessRules/findApiData 500 43.905 ms - 151

我期待的是一条消息" Hello World"来自index.js中的函数exports.findApiData。

请帮助我理解并解决这个问题!

在NodeJS服务器上,我使用以下文件:

  • Router.js(用于设置路由,此处也在调用index.js中的函数)
  • App.js(配置)
  • BusinessRules / index.js(处理请求页面请求)

在客户端:

function getNewValue(t,e){

 if (e.keyCode == 13){
   newValue =  '{"_id": "' + id + '","' + $th + '": "' + t.ltrim() + "}';
   var jsonNewValue = JSON.parse(newValue);
   $.ajax({
           url:'/BusinessRules/findApiData',
           type:'POST',
           contentType: 'application/json',
                  data: jsonNewValue });
          }
 }

Router.js

  app.post('/BusinessRules/findApiData', require('./views/BusinessRules/index').findApiData);

index.js [已编辑]

'use strict'
exports.find = function(req, res, next){
    console.log("find");
    req.query.lookupValue = req.query.lookupValue ? req.query.lookupValue : '';
    req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20;
    req.query.page = req.query.page ? parseInt(req.query.page, null) : 1;
    req.query.sort = req.query.sort ? req.query.sort : '_id';

    var filters = {};
    if (req.query.lookupValue) {
        filters.lookupValue = new RegExp('^.*?'+ req.query.lookupValue +'.*$', 'i');
    }

    req.app.db.models.BusinessRules.pagedFind({
        filters: filters,
        keys: 'lookupValue  tagCattegory  tagScore  typeBusinessRule  _id',
        limit: req.query.limit,
        page: req.query.page,
        sort: req.query.sort
    }, function(err, results) {
        if (err) {
            return next(err);
        }

        if (req.xhr) {
            res.header("Cache-Control", "no-cache, no-store, must-revalidate");
            results.filters = req.query;
            console.log("Results XHR ");
            res.send(results);
            res.json(results);
        }
        else {
            results.filters = req.query;
            //res.json(results);
            console.log("Results No XHR ");
            //console.log(results);
            res.render('BusinessRules/index', { data: results.data });


        }

    });
};

exports.read = function(req, res, next){
    req.app.db.models.BusinessRules.findById(req.params.id).exec(function(err, BusinessRules) {
        if (err) {
            return next(err);
        }

        if (req.xhr) {
            res.send(BusinessRules);
        }
        else {
            res.render('BusinessRules/details', { BusinessRules: BusinessRules });
        }
    });
};

exports.add = function(req, res){
    res.render('BusinessRules/add');
};

exports.create = function(req, res, next) {
    console.log('START POST: ');
    var workflow = req.app.utility.workflow(req, res);

    workflow.on('validate', function() {
        console.log('START POST(1) IF FORM CHECK: ');
        if (!req.body.lstTypeBusinessRule) {
            workflow.outcome.errors.push('Please enter a TypeBusinessRule.');
            console.log('TypeBusinessRule niet gevuld');
            return workflow.emit('response');
        }
        workflow.emit('createBusinessRule');
    });

    workflow.on('createBusinessRule', function () {
        console.log('STAR POST (3):Worflow On:');
        var fieldsToSet = {
            typeBusinessRule: req.body.lstTypeBusinessRule,
            lookupValue: req.body.txtLookupValue,
            tagCattegory: req.body.txtTagCattegory,
            tagScore: req.body.txtTagScore,
            creationDate: Date()
        };
        console.log(fieldsToSet);

        req.app.db.models.BusinessRules.create(fieldsToSet, function(err, BusinessRule) {
            if (err) {
                return workflow.emit('exception', err);
            }

            workflow.outcome.record = BusinessRule;
           // req.flash('success','BusinessRule Added');
            res.location('/BusinessRules');
            res.redirect('/BusinessRules');
        });
    });
    workflow.emit('validate');
};

exports.findApiData = function (req, res, next) {
    console.log("Hallo Erik");
    res.send("Hello World");
};

App.js [已编辑]

'use strict';

//dependencies
var config = require('./config'),
    express = require('express'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    mongoStore = require('connect-mongo')(session),
    http = require('http'),
    path = require('path'),
    passport = require('passport'),
    mongoose = require('mongoose'),
    helmet = require('helmet');
 //   csrf = require('csurf');

//create express app
var app = express();

//keep reference to config
app.config = config;

//setup the web server
app.server = http.createServer(app);

//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
  //and... we have a data store
});

//config data models
require('./models')(app, mongoose);

//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: config.cryptoKey,
  store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
//app.use(csrf({ cookie: { signed: true } }));
helmet(app);

//response locals
app.use(function(req, res, next) {
 // res.cookie('_csrfToken', req.csrfToken());
  res.locals.user = {};
  res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
  res.locals.user.username = req.user && req.user.username;
  next();
});

//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';

//setup passport
require('./passport')(app, passport);

//setup routes
require('./routes')(app, passport);

//custom (friendly) error handler
app.use(require('./views/http/index').http500);

//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');

//listen up
app.server.listen(app.config.port, function(){
  //and... we're live
  console.log('Server is running on port ' + config.port);
});

1 个答案:

答案 0 :(得分:0)

<强>解

感谢评论,我通过stringify JSON对象解决了这个问题。我不知道为什么需要这样做。但它的确有效。

function getNewValue(t,e){

 if (e.keyCode == 13){
   newValue =  '{"_id": "' + id + '","' + $th + '": "' + t.ltrim() + "}';
   var jsonNewValue = JSON.parse(newValue);
   $.ajax({
           url:'/BusinessRules/findApiData',
           type:'POST',
           contentType: 'application/json',
                  data: JSON.stringify(jsonNewValue)});
          }
 }