node.js express4无法使用body-parser读取帖子

时间:2014-09-07 01:06:29

标签: node.js express

我无法阅读帖子,我尝试了“application / json”格式的帖子。我尝试了所有内容类型,并在身体解析器中间件中移动,这似乎都没有用。

我对nodejs和stackexchange相当新,感谢您的帮助。感谢。

    var express = require('express');
    var util = require('util');

    var App = function(){
      // Scope
      var self = this;
      // Setup
      self.ipaddr  = process.env.OPENSHIFT_NODEJS_IP|| '127.0.0.1';
      self.port    = parseInt(process.env.OPENSHIFT_NODEJS_PORT|| 3000) ;
      if (typeof self.ipaddr === "undefined") {
        console.warn('No OPENSHIFT_NODEJS_IP environment variable');
      };
      // Web app urls
      self.app  = express();
      var bodyParser = require('body-parser');
      var methodOverride = require('method-override');
      // parse application/x-www-form-urlencoded
      self.app.use(bodyParser.urlencoded({extended: true}));
      // parse application/json
      self.app.use(bodyParser.json());
      // override with POST having ?_method=DELETE
      self.app.use(methodOverride('_method'))

      self.app.post('/', function(req, res){
        console.log(util.inspect(req, false, null));
        console.log(req.body.username);
        console.log('post');
        res.end('success');
      });

      //starting the nodejs server with express
      self.startServer = function(){
        self.app.listen(self.port, self.ipaddr, function(){
          console.log('%s: Node server started on %s:%d ...', Date(Date.now()), self.ipaddr, self.port);
        });
      }

      // Destructors
      self.terminator = function(sig) {
        if (typeof sig === "string") {
          console.log('%s: Received %s - terminating Node server ...',         Date(Date.now()), sig);
          process.exit(1);
        };
        console.log('%s: Node server stopped.', Date(Date.now()) );
      };

      process.on('exit', function() { self.terminator(); });

      self.terminatorSetup = function(element, index, array) {
        process.on(element, function() { self.terminator(element); });
      };

      ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGTERM'].forEach(self.terminatorSetup);

    };

    //make a new express app
    var app = new App();

    //StartServer
    app.startServer();

0 个答案:

没有答案