json 无法从始终未定义的JavaScript对象读取值

hivapdat  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(95)

我无法从JavaScript对象中检索值。
我已经尝试了几种方法,但我不能让它工作的通常方式,我现在,但我是相当新的javaScript。
感谢您的时间和关注,如果有任何遗漏或您需要一些更多的信息,请与我联系。

    • 对象**表单 * 合并日志(未打包请求)*
{
 'mFile ': {
    name: 'test',
    data: { type: 'Buffer', data: [Array] },
    size: 4,
    encoding: '7bit',
    tempFilePath: '',
    truncated: false,
    mimetype: 'application/octet-stream',
    md5: '098f6bcd4621d373cade4e832627b4f6'
  }
}

我的代码:

app.post('/single', async(req, res, next) => {
try {
    
    const unpackedReq = JSON.parse(JSON.stringify(req.files));
    const file = unpackedReq.mFile

    console.log(unpackedReq)
    console.log(typeof(unpackedReq)) //object
    console.log(unpackedReq["mFile"].name) // TypeError: Cannot read properties of undefined (reading 'name')

} catch (error) {
    console.log(error)
    res.send('Error uploading file')
}

完整错误:

> TypeError: Cannot read properties of undefined (reading 'name')
>     at /Users/lukasbronstering/VsCode/ftp-web-server/app.js:25:42
>     at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)
>     at next (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/route.js:144:13)
>     at Route.dispatch (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/route.js:114:3)
>     at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)
>     at /Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:284:15
>     at Function.process_params (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:346:12)
>     at next (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:280:10)
>     at jsonParser (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/body-parser/lib/types/json.js:119:7)
>     at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)
oipij1gg

oipij1gg1#

对象'mFile '中有一个空格,而您访问它时没有空格。
所以你可以只添加空格同时访问你的对象象console.log(unpackedReq["mFile "].name)或者你可以改变你的对象.但是我建议改变你的对象名

相关问题