简体   繁体   English

Express JS中的路径参数

[英]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. 我正在使用Express JS处理路由http://localhost:3000/location ,该路由允许混合使用参数和固定端点。 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是该路由的根,它呈现位置列表的视图。

http://localhost:3000/location/map renders a view for a list of the locations drawn on a web map. http://localhost:3000/location/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. http://localhost:3000/location/:id包含URL中给定位置ID的参数,调用该参数时,将呈现一个视图,以查看来自数据库查询的给定位置的详细信息。

'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? 更具体地说,如何正确处理当我调用“ http:// localhost:3000 / location / SOMETHINGWRONG ”时出现的问题,例如,触发了http://localhost:3000/location/:id导致数据库查询错误,因为“ SOMETHINGWRONG”不是整数并且无法通过?

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 如果符合规则,请输入方法,其中“ id”是一个数字,包含12个字符

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 (()). 若要更好地控制可以由route参数匹配的确切字符串,可以在括号(())中附加一个正则表达式。 ex: Your Id is an integer with a maximum length of 10 characters 例如:您的ID是一个整数,最大长度为10个字符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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