Node / Express.js请求处理不同的文件

时间:2013-12-12 12:13:46

标签: node.js express middleware

// server.js

app.use('/shelf', require('./books').middleware);

// books.js

var app = new express.Router();

app.post('/books' , function (req, res) {
console.log('here');
});

module.exports = app;

这是我到目前为止所做的;我的服务器在server.js下运行,当我发出'/ shelf / books'请求时,它首先转到server.js然后转到books.js文件并记录'here'。但我想添加一个请求处理程序(一个不同的文件,handler.js,即),我想验证post param是否为数字,如果是,则将其重定向到books.js。

2 个答案:

答案 0 :(得分:0)

这个怎么样?

// handler.js

module.exports = function (req, res, next) {
    req.check_result = /\d+/.test(req.body.yourfield); 
};

// book.js

app.post('/books' , function (req, res) {
    if(req.check_result) {
        // your code
    } else {
        // your code
    }
});

// server.js

app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);

答案 1 :(得分:0)

<强> app.js

var express = require('express')
  , http = require('http')

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());

app.use(require('./handler').middleware);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

<强> handler.js

var express = require('express')
var books = require('./books')

var router = new express.Router();

router.get('/shelf/:book_id', function(req, res){
  var onlyNumbers =req.param('book_id').match(/^\d+$/)
  if (onlyNumbers){
    var parsedNumber = parseInt(req.param('book_id'));
    if( parsedNumber ) {
      books(parsedNumber)
      console.log("Parsed number is : " + parsedNumber)
      res.end("Parsed number is : " + parsedNumber) 
    }
  }
  else {
      console.log("not a number : " + req.param('book_id')) 
      res.end("not a number : " + req.param('book_id'))
    }

  res.end('');
})

module.exports = router;

<强> books.js

var express = require('express')

var app = new express.Router();


module.exports = function(req, res) {
  console.log("\t in books module")
};