Error in implementing router

时间:2015-06-30 13:48:18

标签: node.js express

Here is my code.

server.js

var express = require('express'),
    bodyParser = require('body-parser'),
    log = require('./libs/log')(module),
    api = require('./libs/api.js'),
    app = express();

// settings
app.set('port', 5000);

// to process post requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// routes
rawQuestionRouter = require('./routes/rawQuestionRoutes.js');
app.use('/rawQuestions', rawQuestionRouter);

and routes/rawQuestionRoute.js:

var express = require('express');

var routes = function() {
  var rawQuestionRouter = express.Router();

  rawQuestionRouter.route('/test')
    .post(function(request, response) {
      log.debug(request.body);
      response.send('raw question saved');
    });

    return rawQuestionRouter;
}

module.exports = routes;

Update:

When I make a POST request on '/rawQuestions/test' the server don't respond. Why?

1 个答案:

答案 0 :(得分:3)

您正在导出routes功能,该功能不是路由器(返回一个,但不一样)。

有几种解决方案:

// server.js
app.use('/rawQuestions', rawQuestionRouter());

或者:

// routes/rawQuestionRoute.js
module.exports = routes();

或者只是完全删除整个routes功能并直接导出路由器实例。