ale*_*xtc 1 javascript routes node.js express
http://localhost:3000/location我正在使用 Express JS 来处理允许混合参数和固定端点的路由。例如:
http://localhost:3000/location是路线的根,它呈现位置列表的视图。
http://localhost:3000/location/map呈现 web 地图上绘制的位置列表的视图。
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;
Run Code Online (Sandbox Code Playgroud)
这是处理具有混合固定值和参数化参数的路由的最佳实践吗?
更具体地说,如何正确处理当我调用“ http://localhost:3000/location/SOMETHINGWRONG ”时触发的问题,http://localhost:3000/location/:id该问题导致数据库查询错误,因为“SOMETHINGWRONG”不是整数并且无法经过?
您可以在路由中使用正则表达式限制规则,例如,如果您只希望收到整数,则可以使用如下内容:
router.get('/:id(\\d{12})', (req, res) => {
//...
});
Run Code Online (Sandbox Code Playgroud)
如果符合规则,请输入方法,其中“id”是12个字符的数字
仅验证数字:
app.get('/:id(\\d+)', function (req, res){
//...
});
Run Code Online (Sandbox Code Playgroud)