javascript - Express 4 中路径参数中的 Json 对象
问题描述
要求是在从快递中的 req 对象接收到的参数中具有对象结构。
例如:
/users/items[\:]id-:id/items[\:]type-:type
在这方面,我得到低于价值req.params
{
id: 1,
type: 'general'
}
当与/users/items:id-1/items:type-general
有没有办法得到它,如下所示:
{
items:{
id: 1,
type: 'general'
}
}
编辑
另一个支持的示例路线: /users/items:id-1/boxes:type-general
{
items:{
id: 1,
},
boxes:{
type: 'general'
}
}
解决方案
你可以试试类似的东西。
app.param(['id', 'type'], (req, res, next, value, key) => {
req.params.items = req.params.items ? req.params.items : {};
req.params.items[key] = value;
// Removing the default properties which gets added.
delete req.params[key];
next();
});
这将帮助您更改 req.params 中的键。
参考:https ://expressjs.com/en/4x/api.html#app.param
[或者]
另一种方法是针对您编辑的问题使用中间件。你可以尝试类似的东西
const getParamsAsJSONObject = (req, res, next) => {
const [emptypart, ...parts] = req.url.split('/');
console.log(parts);
req.customParams = parts.reduce((paramsObj, currentPart) => {
console.log(paramsObj);
console.log(currentPart);
const [parentKey, childKeyValue] = currentPart.split(':');
paramsObj[parentKey] = paramsObj[parentKey] ? paramsObj[parentKey] : {};
const [childKey, childValue] = childKeyValue.split('-');
paramsObj[parentKey][childKey] = childValue;
return paramsObj;
}, {});
next();
};
app.use('/users', getParamsAsJSONObject, (req, res, next) => {
console.log(req.customParams);
// Remaining Piece of the code to be added.
});
推荐阅读
- javascript - 使用 joi.assert 或 joi.attempt 时出现“TypeError:schema.validate 不是函数”
- javascript - 条件格式运行正常
- c++ - QT:断言:文件 C:\Qt\Qt5.14.2\5.14.2\mingw73_64\include/QtCore/qstring.h 中的“uint(i) < uint(size())”,第 1029 行
- c# - 从 url 或没有随机写入行
- python - 在编译这个贪婪算法的 python 问题时遇到问题
- kotlin - 当实体字段在 Kotlin 类中可以为空时,是否可以使 Room SQLite 列不为空?
- python - 在 Python 中合并图像
- reactjs - 媒体查询在检查员中有效,但在手机上无效
- tensorflow - 具有多个隐藏层的 TensorFlow 2 GRU 层
- reactjs - React-Select isMulti 检索选择的选项