NodeJs Restful API没有返回参数标识

时间:2016-09-08 17:24:27

标签: node.js mongodb express

我正在使用nodejs / express / mongodb构建一个restful API。我正在尝试实施短信验证,以便用户能够通过短信接收代码以验证帐户。

我无法从此路线网址返回req.params.id。

http://localhost:3000/api/account/123/sms/

路由

app.use('/api/account', require('./app/routes/account.route'));
app.use('/api/account/:id/sms', require('./app/routes/sms.route'));

account.route

'use strict';

var express    = require('express');
var router     = express.Router();
var controller = require('../controllers/account.controller');
controller     = new controller();

router.get('/', controller.index.bind(controller));
router.get('/:id', controller.show.bind(controller));
router.post('/', controller.store.bind(controller));
router.put('/:id', controller.update.bind(controller));
router.delete('/:id', controller.destroy.bind(controller));

module.exports = router;

sms.route

'use strict';

var express    = require('express');
var router     = express.Router();
var controller = require('../controllers/sms.controller');
controller     = new controller();

router.post('/', controller.store);

module.exports = router;

sms.controller

'use strict';

var User   = require('../models/user.model');
var Token  = require('../models/token.model');
var config = require('../../config/app');
var SMS = require('../../modules/sms');

class SmsController {

    store(req, res) {

        return res.json(req.params.id);

    }
}

module.exports = SmsController;

我正在使用邮递员尝试点击该端点(网址)。我期待它返回123帐户ID,但它没有返回/空/空白。

1 个答案:

答案 0 :(得分:0)

感谢@robertklept关于合并params的评论,我知道你之前可以做到这一点,我设法在搜索快速合并参数后解决它

所以基本上我需要将我的短信路由器嵌入我的帐户路由器中。然后在定义我的短信路由器时设置mergeparams的可选值。

路由

module.exports = function(app){

    app.use('/api/account', require('./app/routes/account.route'));

};

account.route

'use strict';

var express    = require('express');
var router     = express.Router();
var controller = require('../controllers/account.controller');
controller     = new controller();

router.get('/', controller.index.bind(controller));
router.get('/:id', controller.show.bind(controller));
router.post('/', controller.store.bind(controller));
router.put('/:id', controller.update.bind(controller));
router.delete('/:id', controller.destroy.bind(controller));

router.use('/:id/sms', require('./sms.route'));

module.exports = router;

sms.route

'use strict';
var express    = require('express');
var router     = express.Router({mergeParams: true});
var controller = require('../controllers/sms.controller');
controller     = new controller();

router.post('/', controller.store);

module.exports = router;