Kamuran Sönecek
Kamuran Sönecek

Reputation: 3333

Nodejs Express Multiple Parameters Not Work Well

I want to get two parameters from nodejs express but when I defined parameters as the below, I faced an issue and I could not solve it. My codes are these for routing:

app.use('/api/upcomingEvents/:trader/:id', require('./api/upcomingEvent'));
/* ther are inside of upocomingEvent/index.js */
var express = require('express');
var controller = require('./upcomingEvent.controller');
var router = express.Router();
router.get('/:trader/:id', controller.index);

When I send a request according to the defined routing, It give me the just first paramater. For example :

http://www.sitename.com/api/upcomingEvents/firstTrader/1

For this path express parameters like this {trader:1,id:undefined}

If I change the path like this :

http://www.sitename.com/api/upcomingEvents/blablabla/firstTrader/1

It return the parameters as I want : {trader:'firstTrader',id:1}

How can I solve this problem?

api/UpcomingEvent/index.js :

var express = require('express');
var controller = require('./upcomingEvent.controller');

var router = express.Router();

router.get('/:trader', controller.index);
router.get('/:trader/:id', controller.index);
router.post('/:trader', controller.index);
router.post('/:trader/:id', controller.index);
module.exports = router;

api/upcomingEvent/upcomingEvent.controller.js:

'use strict';
  // Gets a list of UpcomingEvents
exports.index = function(req, res) {
    console.log(req.params);
    res.send(200,"ok!"); return;
};

Upvotes: 0

Views: 415

Answers (1)

robertklep
robertklep

Reputation: 203519

In api/upcomingEvent.js, you are declaring the same parameters again. In essence, you're creating routes to match this:

/api/upcomingEvents/:trader/:id/:trader
/api/upcomingEvents/:trader/:id/:trader/:id

Try this instead:

// app.js
app.use('/api/upcomingEvents', require('./api/upcomingEvent'));

// api/upcomingEvent.js
router.get ('/:trader',     controller.index);
router.get ('/:trader/:id', controller.index);
router.post('/:trader',     controller.index);
router.post('/:trader/:id', controller.index);

Since :id is optional, you can even shorten that to:

router.get ('/:trader/:id?', controller.index);
router.post('/:trader/:id?', controller.index);

Upvotes: 2

Related Questions