简体   繁体   中英

Route parameters in Express JS

I am using Express JS to handle a route http://localhost:3000/location which allows a mix of parameters and fixed endpoints. For example:

http://localhost:3000/location is the root for the route, which renders a view for a list of locations.

http://localhost:3000/location/map renders a view for a list of the locations drawn on a web map.

http://localhost:3000/location/:id contains a parameter for the ID of a location given in the URL and when called, renders a view for the details of the given location that comes from a database query.

'use strict';

var path = require('path');
var express = require('express');
var router = express.Router();

/* GET route root page. */
router.get('/', function(req, res, next) {
  // DO SOMETHING
});

/* GET the map page */
router.get('/map', function(req, res, next) {
  // DO SOMETHING
});

/* GET individual location. */
router.get('/:id', function(req, res, next) {
  // DO SOMETHING
});

module.exports = router;

Is this a best practise for handling a route with mixed fixed values and parameterized parameters?

More specifically, how to properly handle the problem that when I called " http://localhost:3000/location/SOMETHINGWRONG ", for example, http://localhost:3000/location/:id was triggered which led to a database query error because "SOMETHINGWRONG" was not an integer and could not pass?

You can restrict a rule with regex in your route, for example, if you only expect to receive whole numbers, you can use something like this:

router.get('/:id(\\d{12})', (req, res) => {
//...
});

enter the method if you meet the rule, where "id" is a number and of 12 characters

Validate only numbers:

app.get('/:id(\\d+)', function (req, res){ 
...
});

To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (()). ex: Your Id is an integer with a maximum length of 10 characters

/* GET individual location. */
router.get('/:id([0-9]{1,10})', function(req, res, next) {
  // DO SOMETHING
});

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