javascriptjsonexpress

Cant read vaules from JavaScript Object always undefined


I can't retrieve values from a JavaScript object.

I have tried several ways but I can't get it to work the usual way i now but i am pretty new in javaScript.

Thanks for your time and attention, if there is anything missing or you need some more information please contact me.

The object from console.log(unpackedReq)

{
 'mFile ': {
    name: 'test',
    data: { type: 'Buffer', data: [Array] },
    size: 4,
    encoding: '7bit',
    tempFilePath: '',
    truncated: false,
    mimetype: 'application/octet-stream',
    md5: '098f6bcd4621d373cade4e832627b4f6'
  }
}

My code:

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')
}

The full error:

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)


Solution

  • There is a space in object 'mFile ' and you're accessing it without space.

    so you can just add the space while accessing your object like this console.log(unpackedReq["mFile "].name) or you could change your object. but i would recommend to change your object name