网址编码
我看到的代码中的第一个问题(我猜?)是您使用& 而不是? 来启动查询参数;我们使用& 来分隔键值对(如foo=bar&baz=hello)。因此,您可能需要检查一次。
如果您将& 更改为?,您可以使用req.query.<objectName> 访问它。
其他解决方案
我也只是您的编辑,为此我们可以使用/house/:id/:country/:stateAndZip,我们需要进行一些更改。
我可能会使用这种方法:
const { stateAndZip } = req.params;
const [ state, zipCode ] = stateAndZip.split( '&' );
// Here, state contains 'ny' and `zipCode` is of the work `zipcode=XXXXX`.
const [ , formattedZipCode ] = zipCode.split( '=' ); // Or use https://nodejs.org/api/querystring.html
// formattedZipCode is XXXXX.
此解决方案存在一些问题;第一个是假设zipcode 是& 之后的第一个参数。如果您想要更通用的方法,请告诉我。
更好的解决方案
从上面获取解决方案并假设我们有一个无序列表,其中zipcode 可以在任何地方,我们可以执行以下操作:
const qs = require( 'querystring' );
const { stateAndZip } = req.params;
const [ state, queryParams ] = stateAndZip.split( '&' );
const decodedQueryParams = qs.parse( queryParams );
// decodedQueryParams will be an object with the property `zipcode`.
这里的一个问题是我们可能在 URL 本身中有一个 & 符号 (&),您可以通过假设所有状态名称的缩写形式只有 2 个字符并读取到 @ 987654335@,并使用querystring解析出剩余的字符串。