简体   繁体   中英

Error in implementing router

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?

You're exporting the routes function, which is not a router (it returns one, but that's not the same).

There are several solutions:

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

Or:

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

Or just remove the entire routes function altogether and export the router instance directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM