问题
I currently have 2 routes in node.js for an API I am building. They are:
app.get('/api/v1/user/:userid', function (req, res) {
return res.status(200).json(GetUser());
});
and
app.get('/api/v1/user', function (req, res) {
return res.status(400).json('UserId expected');
});
As you can see, both routes actually should be combined into one, for example:
app.get('/api/v1/user/:userid', function (req, res) {
console.log('this should still show if :userid is not populated, but it does not');
if(!req.params.userid)
return res.status(400).json('UserId expected');
return res.status(200).json(GetUser());
});
However, when I test the above endpoint with Postman without the :userid
specified, I will get a timeout. Obviously if I supply an :userid
, I get the corresponding user.
Also I have found that the console.log
will never show up in the terminal when :userid
isn't specified. This is my terminal output:
this should still show if :userid is not populated, but it does not
GET /api/v1/user/56a6861675774c1a046bf780 200 3.140 ms - 274
GET /api/v1/user/ - - ms - -
So all the above leads me to believe that because the :userid
is undefined
or null
, that it is breaking the express middleware. Is that assumption correct and how do I overcome it?
回答1:
The assumption is correct. The handler defined for /api/v1/user/:user_id
cannot be used for /api/v1/user
. As such, the route /api/v1/user/
will be unable to handle 'GET' requests.
You need to define different handlers for the different routes.
A solution would be to use Express router middleware to define your routes.
var router = express.Router();
router.route('/api/v1/user')
.get(); // define handler for multiple resources here.
router.route('/api/v1/user/:user_id')
.get(); // define handler for single resource here.
app.use('/', router);
来源:https://stackoverflow.com/questions/35119662/node-js-express-routing-with-parameters