Code function

Describe the issue/error/question

hello

i made a flow that get phone calls, and send a WhatsApp msg back
the problem i am facing is that local phones come without the international code
its comes with a zero in the beginning and i am trying to take it down

What is the error message (if any)?

ERROR: Unexpected token โ€˜{โ€™ [line 1]

SyntaxError

Details

Stack

/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code:1
module.exports = async function() {let phoneNumber = {{ $json["body"] }}; // replace with your phone number
                                                      ^

SyntaxError: Unexpected token '{'
    at makeNiceSyntaxError (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/transformer.js:41:16)
    at transformer (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/transformer.js:84:8)
    at Sandbox.run (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/nodevm.js:414:17)
    at Sandbox.runCodeAllItems (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Sandbox.js:36:42)
    at Sandbox.runCode (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Sandbox.js:30:62)
    at Object.execute (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Code.node.js:75:39)
    at Workflow.runNode (/usr/local/lib/node_modules/n8n/node_modules/n8n-workflow/dist/Workflow.js:658:51)
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/WorkflowExecute.js:590:68
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Code

Parameters


Docs

Mode

JavaScript

1

2

3

4

5

6

7

8

โŒ„

let phoneNumber = {{ $json[โ€œbodyโ€] }}; // replace with your phone number

if (phoneNumber.startsWith(โ€œ0โ€)) {

phoneNumber = phoneNumber.replace(/^0/, โ€œ972โ€);

}

console.log(phoneNumber); // prints โ€œ972123456789โ€ if the phone number starts with โ€œ0โ€

Type $ for a list of special vars/methods. Debug by using console.log() statements and viewing their output in the browser console.

I wish this node wouldโ€ฆ

Please share the workflow

{
  "meta": {
    "instanceId": "47f5ac7342afa257a5ec2d7bd6adb9c0c35d64b417d63ccdf634a9f92b43fc23"
  },
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "cannabis_shefa",
        "options": {}
      },
      "id": "7d8c7c30-d6f6-4543-b70f-e79052168634",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        880,
        -20
      ],
      "webhookId": "ca1e61b0-12c2-47c9-b888-6e204e472458"
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "operation": "isEmpty"
            }
          ]
        }
      },
      "id": "f0f69591-e2df-458d-9842-b63bf02c237d",
      "name": "IF2",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1420,
        -20
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "operation": "lookup",
        "sheetId": "1i7APbeC6-y2C4fVf7FpLbM_Jo8ZKarZykZIagla57Bw",
        "range": "A:B",
        "lookupColumn": "phone",
        "lookupValue": "={{$json[\"phone\"]}}",
        "options": {
          "returnAllMatches": true,
          "valueRenderMode": "FORMATTED_VALUE"
        }
      },
      "name": "bened",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 1,
      "position": [
        1240,
        -20
      ],
      "alwaysOutputData": true,
      "id": "2fdf3f77-832c-4f46-a851-4c50f4625e50",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "31",
          "name": "Google Sheets shefa pharm"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://xn--4dbkaanh8a2dvb.com/api/contact_groups.php",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "contact",
              "value": "={{ $item(\"0\").$node[\"test\"].json[\"phone\"] }}"
            },
            {
              "name": "type",
              "value": "add"
            },
            {
              "name": "group_id",
              "value": "2"
            },
            {
              "name": "access_token"
            }
          ]
        },
        "options": {}
      },
      "id": "840ae540-6921-4c38-bf2e-e051c9a5ba7a",
      "name": "add to list",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1620,
        -40
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "operation": "lookup",
        "sheetId": "1d1cyHWY87DnuKyFf6SAt6FJFIjrTF76nOdDBeFmWSR4",
        "range": "A:B",
        "lookupColumn": "phone",
        "lookupValue": "={{$json[\"phone\"]}}",
        "options": {
          "returnAllMatches": true,
          "valueRenderMode": "FORMATTED_VALUE"
        }
      },
      "name": "first time caller",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 1,
      "position": [
        860,
        220
      ],
      "alwaysOutputData": true,
      "id": "d0a288b8-ecb2-4a8a-a5e0-b695b121261a",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "31",
          "name": "Google Sheets shefa pharm"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "operation": "isEmpty"
            }
          ]
        }
      },
      "id": "edac770a-6d32-44f6-831e-35029b1c0960",
      "name": "if exsist",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1020,
        220
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://xn--4dbkaanh8a2dvb.com/api/send.php",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "number",
              "value": "={{ $item(\"0\").$node[\"Set country phone\"].json[\"phone\"] }}"
            },
            {
              "name": "type",
              "value": "check_phone"
            },
            {
              "name": "instance_id"
            },
            {
              "name": "access_token"
            }
          ]
        },
        "options": {}
      },
      "id": "abdeb2ff-9b07-4e9d-b7ac-4986def91706",
      "name": "check if has android",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1260,
        200
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "operation": "append",
        "sheetId": "1d1cyHWY87DnuKyFf6SAt6FJFIjrTF76nOdDBeFmWSR4",
        "range": "A:B",
        "options": {}
      },
      "name": "add to caller list",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 1,
      "position": [
        1880,
        200
      ],
      "alwaysOutputData": true,
      "id": "2a786eb4-add2-4e23-9574-dbb0ac178da5",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "31",
          "name": "Google Sheets shefa pharm"
        }
      }
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "phone",
              "value": "={{ $item(\"0\").$node[\"Set country phone\"].json[\"phone\"] }}"
            },
            {
              "name": "time",
              "value": "={{ $now}}"
            }
          ]
        },
        "options": {}
      },
      "id": "29fe28c1-6ece-40a8-836a-7e4e897be449",
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [
        1680,
        200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://xn--4dbkaanh8a2dvb.com/api/send.php",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "number",
              "value": "={{ $item(\"0\").$node[\"test\"].json[\"phone\"] }}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "message",
              "value": "*ื‘ืจื•ืš ื”ื‘ื ืœืงื ืื‘ื™ืกืคื•ืŸ ืฉืคืข ืคืืจื  ืื ื™ ืฉืžื— ืฉื”ืฆื˜ืจืคืช,  ืื ื™ ืฉื•ืœื— ืœืš ืืช ื”ืชืคืจื™ื˜ ื”ืขื“ื›ื ื™ ืฉืœื ื•,  ืื ื™ ืžืžืœื™ืฅ ืœืฉืžื•ืจ ืื•ืชื• ืขื ื›ื•ื›ื‘,  *ืฉื™ื ืขื™ืŸ ืขืœ ื”ืคื™ื ื” ืฉืœ ื”ืžื‘ืฆืขื™ื ื‘ืชืคืจื™ื˜*.  *ืžื—ื›ื™ื ืœืš ื‘ืฉืคืข shefa.weedex.co.il  ืฉืคืข ืคืืจื"
            },
            {
              "name": "access_token"
            }
          ]
        },
        "options": {}
      },
      "id": "e10f48ec-e3ac-418d-a7dc-0907201ed927",
      "name": "send first msg",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1460,
        200
      ]
    },
    {
      "parameters": {
        "jsCode": "let phoneNumber = {{ $json[\"body\"] }}; // replace with your phone number\n\nif (phoneNumber.startsWith(\"0\")) {\n  phoneNumber = phoneNumber.replace(/^0/, \"972\");\n}\n\nconsole.log(phoneNumber); // prints \"972123456789\" if the phone number starts with \"0\"\n"
      },
      "id": "266c0d86-0596-419b-b75b-f5b1361aff27",
      "name": "Code",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        1080,
        -20
      ]
    },
    {
      "parameters": {
        "values": {
          "number": [
            {
              "name": "phone",
              "value": "=972{{ $item(\"0\").$node[\"Webhook\"].json[\"body\"] .split('0')[1]}}\n{{input.all = $item(\"0\").$node[\"Webhook\"].json[\"body\"]; // replace with your phone number\n\nif (phoneNumber.startsWith(\"0\")) {\n  phoneNumber = phoneNumber.replace(/^0/, \"972\");\n}\n\nconsole.log(phoneNumber); // prints \"972123456789\" if the phone number starts with \"0\"}}\n{{let results = [];\n\nfor (item of items) {\n    for (key of Object.keys(item.binary)) {\n        results.push({\n            json: {\n                fileName: item.binary[key].fileName\n            },\n            binary: {\n                data: item.binary[key],\n            }\n        });\n    }\n}\n\nreturn results;}}\n"
            }
          ]
        },
        "options": {}
      },
      "id": "ddb8785b-ea80-47e9-8d00-e536f67658f6",
      "name": "test",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [
        1000,
        -200
      ]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF2": {
      "main": [
        [
          {
            "node": "add to list",
            "type": "main",
            "index": 0
          },
          {
            "node": "first time caller",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "bened": {
      "main": [
        [
          {
            "node": "IF2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "first time caller": {
      "main": [
        [
          {
            "node": "if exsist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "if exsist": {
      "main": [
        [
          {
            "node": "check if has android",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "check if has android": {
      "main": [
        [
          {
            "node": "send first msg",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set": {
      "main": [
        [
          {
            "node": "add to caller list",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "send first msg": {
      "main": [
        [
          {
            "node": "Set",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code": {
      "main": [
        [
          {
            "node": "bened",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

## Share the output returned by the last node
<!-- If you need help with transforming the data, please also share the expected output -->

## Information on your n8n setup
- **n8n version:**
- **Database you're using (default: SQLite):**
- **Running n8n with the execution process [own(default), main]:**
- **Running n8n via [Docker ]:**

Hey @Yossi_Yhezkel,

When using the code node the data isnโ€™t accessed with {{ $json["body"] }} you would instead need to loop over it. When you first add the code node to the canvas and open it there is an example that shows you how to do it.

Assuming you are sending a body parameter with a name of phonenumber the snippet below will work. You could also do it with an If node and a set node if you didnโ€™t want to use any code.

for (const item of $input.all()) {
  if (item.json.body.phonenumber.startsWith("0")) {
    item.json.body.phonenumber = item.json.body.phonenumber.replace(/^0/, "972");
  }
}
return $input.all();

tnx for the answer

this is the results that i get

ERROR: Cannot read properties of undefined (reading โ€˜phonenumberโ€™) [line 2]

TypeError

What does your input data look like? I have assumed you are sending a value of { โ€˜phonenumberโ€™: โ€˜0123456789โ€™ } but you may need to tweak it to match what you are using.

โ€œphonenumberโ€:
โ€œ0542822755โ€

this is the data

Hey @Yossi_Yhezkel,

The example should work, to confirm can you share the json output of your webhook node?

Stack

TypeError: Cannot read properties of undefined (reading 'phonenumber')
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code:2:22
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code:7:2
    at VM2 Wrapper.apply (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/bridge.js:485:11)
    at Sandbox.run (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/nodevm.js:426:23)
    at Sandbox.runCodeAllItems (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Sandbox.js:36:42)
    at Sandbox.runCode (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Sandbox.js:30:62)
    at Object.execute (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/Code/Code.node.js:75:39)
    at Workflow.runNode (/usr/local/lib/node_modules/n8n/node_modules/n8n-workflow/dist/Workflow.js:658:51)
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/WorkflowExecute.js:590:68
    at runMicrotasks (<anonymous>)

Hey @Yossi_Yhezkel,

The stock doesnโ€™t help it is the json output of the webhook node that will show me what needs to be used.

sorry

[
{
โ€œphonenumberโ€: โ€œ0542822755โ€
}
]

Ah ok so there is no body, update the code to remove .body leaving just item.json.phonenumber and you should be good to go.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.