Skip to content
Back

[SOLVED] Appwrite Function - JSON.parse returns an error

  • 0
  • Functions
Matej
21 Jul, 2023, 11:32

I have appwrite function where I want to create a user.

Payload I am sending via console custom data interface "{\"email\": \"user@example.com\",\"password\": \"example\",\"name\": \"User example\"}"

My code

TypeScript
    if (req.payload) {
        const payload = JSON.parse(res.payload);
        console.log('PAYLOAD PARSED');
        console.log(payload);
        try {
            const promise = await users.create(node_appwrite_1.ID.unique(), payload.email, payload.password, payload.name);
            response.body = promise;
            response.statusCode = 200;
        }
        catch (error) {
            response.body = error;
        }
    }

It fails on JSON.parse from what I can tell ...

TypeScript
SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at module.exports (/usr/code-start/src/index.js:31:30)
    at /usr/local/src/server.js:68:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

But if I would do this in a javascript file

TypeScript
console.log(JSON.parse("{\"email\": \"user@example.com\",\"password\": \"example\",\"name\": \"User example\"}"))

I would get this in the console

TypeScript
// [object Object] 
{
  "email": "user@example.com",
  "password": "example",
  "name": "User example"
}

Am I doing something wrong here? Isn't the payload format correct?

TL;DR
The user is encountering an error with JSON parsing in their Appwrite function. They are trying to create a user using custom data. The error occurs when using `JSON.parse` on `req.payload`. The error message suggests that there is an unexpected token 'u' at position 0. The user shares their code and payload. Another user suggests that there might be a typo and recommends using `req.payload` instead of `res.payload`.
BugProg
21 Jul, 2023, 11:38

Hi @Matej ! Try this:

TypeScript
  const payload = JSON.parse(req.payload ?? "{}");
BugProg
21 Jul, 2023, 11:38

I think is not res but req

Matej
21 Jul, 2023, 11:39

omg yes

Matej
21 Jul, 2023, 11:39

I didn't see that typo

BugProg
21 Jul, 2023, 11:39

šŸ™‚

Matej
21 Jul, 2023, 11:40

Thanks šŸ˜„

Matej
21 Jul, 2023, 11:40

[SOLVED] Appwrite Function - JSON.parse returns an error

BugProg
21 Jul, 2023, 11:40

You are welcome

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