Back

[SOLVED] On accessing properties of payload showing undefined

  • 1
  • Functions
devyank
5 Jun, 2023, 07:29

Hi All,

On accessing properties of payload showing undefined on Appwrite cloud using node.js server sdk

Data:

TypeScript
        messageFor: 'web',
        token: 'test-token',
        userToken: 'test-user-token',
        deviceToken: 'test-device-token'
}```

Sample Code:
```module.exports = async function (req, res) {
  const payload = req.payload;

  res.json({
    messageFor: 'messageFor - ' + payload.messageFor,
    token: 'token - ' + payload.token,
    userToken: 'userToken - ' + payload.userToken,
    deviceToken: 'deviceToken - ' + payload.deviceToken,
  });```

Sample Response:
```{
   "messageFor":"messageFor - undefined",
   "token":"token - undefined",
   "userToken":"userToken - undefined",
   "deviceToken":"deviceToken - undefined"
}```
TL;DR
The user is trying to access properties of a payload but is getting 'undefined' values. It was revealed that the issue was due to the keys in the payload not being wrapped in double quotes. After implementing the necessary changes, the issue was resolved.
devyank
5 Jun, 2023, 08:06

On accessing properties of payload showing undefined

Drake
5 Jun, 2023, 15:01

req.payload is a string. You'll need to parse it

devyank
5 Jun, 2023, 16:54

As per your suggestion, I have implemented the same but getting the below error.

Updated Sample Code

TypeScript
module.exports = async function (req, res) {
  const payload = JSON.parse(req.payload);

  res.json({
    messageFor: 'messageFor - ' + payload.messageFor,
    token: 'token - ' + payload.token,
    userToken: 'userToken - ' + payload.userToken,
    deviceToken: 'deviceToken - ' + payload.deviceToken,
  });

Error Response

TypeScript
SyntaxError: Unexpected token m in JSON at position 10
    at JSON.parse (<anonymous>)
    at module.exports (/usr/code-start/src/index.js:126:24)
    at /usr/local/src/server.js:68:19
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I have google it and found it seems might be due to incorrect json string but couldn't able to identify where I am missing it

Drake
5 Jun, 2023, 17:09

the data you're passing into the function is not valid JSON. you must wrap keys with double quotes

devyank
5 Jun, 2023, 17:31

It worked! Thanks 🫡

devyank
5 Jun, 2023, 17:34

Actually, I followed the sample JSON provided while executing from the console. Their keys are not wrapped with double quotes. Hope it will be fixed

Drake
5 Jun, 2023, 17:38

yes, it has already been fixed in a newer version of Appwrite

Drake
5 Jun, 2023, 17:39

[SOLVED] On accessing properties of payload showing undefined

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more