首页 > 解决方案 > 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'
  }
}

标签: javascriptnode.jsregexexpress

解决方案


你可以试试类似的东西。

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.
});

推荐阅读