【问题标题】:Converting FormData string keys to accessible Json Object将 FormData 字符串键转换为可访问的 Json 对象
【发布时间】:2021-07-18 12:40:58
【问题描述】:

我的前端 (JS) 正在使用 FormData 向我的后端 (Node Typescript) 发送请求(因为 FormData 也包含图像),如下所示:-

在我的 Node 项目中,我目前正在使用 express-fileupload (npm),所以当我记录 req.body 时,我得到的结果是:-

这使得访问对象变得困难,因为我必须执行 req.body['items[0][item][id]'] 而不是 req.body.items[0].item.id。有没有一种方法可以轻松地将 req.body 格式化为可访问的 JSON 对象,如下所示?

{
    orderNo: "A00006",
    items: [
        {
            item: {
                _id: "60dfkwakawn1",
                status: 1,
                model: {
                  ...
                },
                ...
            }
            ...
        }
    ],
    ...
}

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    我之前所做的是将我的非文件数据在客户端转换为 JSON 字符串,然后再将其注入 FormData。

    
    let fd = new FormData();
    /* Non-file data you need to send to the server. */
    fd.append('order', JSON.stringify({orderNo: "A00006", items: [{item: {_id: "60dfkwakawn1"}]}));
    /* File object from my file dom element in uploadEl. */
    fd.append('myFile', uploadEl.files[0]);
    /* Submit the form data, fd, to the server with whatever you are using on the client. */
    

    在服务器上,您需要手动从req 中提取值并将其转换回任何对象:

    let order = JSON.parse(req.body.order);
    

    【讨论】:

      猜你喜欢
      • 2022-12-09
      • 2014-11-28
      • 1970-01-01
      • 2017-09-06
      • 2019-08-27
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多