【发布时间】:2020-03-03 23:03:29
【问题描述】:
我正在为我的 Web 服务类分配作业,但不知道如何处理空 URL 参数。这是我的代码:
app.get('/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce', (req, res) => {
var x = parseInt(req.params['x'])
var cheese = (req.params['cheese'])
var tomatoes = (req.params['tomatoes'])
var salsa = (req.params['salsa'])
var hotsauce = (req.params['hotsauce'])
res.send('You ordered ' + x + ' nacho(s) with ' + cheese + ', ' + tomatoes + ', ' + salsa + ', '
+ hotsauce + '.')})
此代码在填充所有参数后运行良好。但是如果我不想处理 null 参数,例如,salsa 并输入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce
【问题讨论】:
-
真的,如果某些元素是可选的,那么
'/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce'不是构建 URL 的正确方法。您可能应该使用结构为name=value的查询字符串,然后您可以拥有所需的任何参数,并且可以轻松分辨出哪个是哪个。如果这是提交订单,那么它应该是一个 POST 并且数据应该在正文中,并且再次将在name=value表单中。
标签: javascript node.js express web-services url