JavaScript on template fails to Fetch JSON

Hello, I am trying to Fetch a JSON from my API in Node-Red but fail to get the contents.
I have simulated my problem in the following image:

Time stamp will work locally but browsing "/test" will require a URL to get to /response
Please adjust URL at the /Get/Test side before testing
Assistance welcome.
The code follows below:

[
    {
        "id": "664244b99a502b3b",
        "type": "tab",
        "label": "Flow 1",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "1db96b05a975cce0",
        "type": "http response",
        "z": "664244b99a502b3b",
        "name": "httpResponse",
        "statusCode": "",
        "headers": {
            "Access-Control-Allow-Origin": "*"
        },
        "x": 720,
        "y": 360,
        "wires": []
    },
    {
        "id": "dc5fed152c7ce697",
        "type": "template",
        "z": "664244b99a502b3b",
        "name": "httpFormat",
        "field": "payload",
        "fieldType": "msg",
        "format": "handlebars",
        "syntax": "mustache",
        "template": "{\n    \"credits\": \"credits\",\n    \"property\":\"property\",\n    \"final\":\"final\",\n    \"city\":\"city\",\n    \"uf\":\"uf\",\n    \"man\":\"man\",\n    \"model\":\"model\",\n    \"year\":\"year\",\n    \"cor\":\"cor\",\n    \"situation\":\"situation\"    \n}",
        "output": "json",
        "x": 530,
        "y": 340,
        "wires": [
            [
                "1db96b05a975cce0",
                "7025b429af244030"
            ]
        ]
    },
    {
        "id": "7025b429af244030",
        "type": "debug",
        "z": "664244b99a502b3b",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 710,
        "y": 320,
        "wires": []
    },
    {
        "id": "7ea5fdfeeff75920",
        "type": "node-red-contrib-http-custom-port",
        "z": "664244b99a502b3b",
        "name": "",
        "url": "/response",
        "method": "get",
        "upload": false,
        "swaggerDoc": "",
        "port": "3100",
        "x": 300,
        "y": 340,
        "wires": [
            [
                "dc5fed152c7ce697"
            ]
        ]
    },
    {
        "id": "ef49e23bb36ad416",
        "type": "node-red-contrib-http-custom-port",
        "z": "664244b99a502b3b",
        "name": "",
        "url": "/test",
        "method": "get",
        "upload": false,
        "swaggerDoc": "",
        "port": "3000",
        "x": 300,
        "y": 260,
        "wires": [
            [
                "6ff4d35fb0e3aec6"
            ]
        ]
    },
    {
        "id": "6ff4d35fb0e3aec6",
        "type": "template",
        "z": "664244b99a502b3b",
        "name": "",
        "field": "payload",
        "fieldType": "msg",
        "format": "handlebars",
        "syntax": "mustache",
        "template": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n    <title>JSON Test</title>\n</head>\n<body>\n    <div id=\"myData\"></div>\n    <script>\n        fetch('Server URL:3100/response')\n            .then(function (response) {\n                return response.json();\n            })\n            .then(function (data) {\n                appendData(data);\n            })\n            .catch(function (err) {\n                console.log('error: ' + err);\n            });\n        function appendData(data) {\n            var mainContainer = document.getElementById(\"myData\");\n            for (var i = 0; i < data.length; i++) {\n                var div = document.createElement(\"div\");\n                div.innerHTML = 'Name: ' + data[i].credits + ' ' + data[i].marca;\n                mainContainer.appendChild(div);\n            }\n        }\n    </script>\n</body>\n</html>",
        "output": "str",
        "x": 540,
        "y": 240,
        "wires": [
            [
                "806968dacc5db796"
            ]
        ]
    },
    {
        "id": "806968dacc5db796",
        "type": "http response",
        "z": "664244b99a502b3b",
        "name": "httpResponse",
        "statusCode": "",
        "headers": {
            "Access-Control-Allow-Origin": "*"
        },
        "x": 720,
        "y": 240,
        "wires": []
    },
    {
        "id": "088ffc4886be3459",
        "type": "inject",
        "z": "664244b99a502b3b",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 300,
        "y": 200,
        "wires": [
            [
                "6ff4d35fb0e3aec6"
            ]
        ]
    }
]

Many in the forum (including me) will not be able to help since you are using a contrib node that it not very common. Did you try your flow with the built-in http nodes ?

Hi, port 80 is already in use so I had to find a way around and found this very useful node.
Hope my problem is not due to this.
I am using regular nodes at httResponse.

ok, in your environment port 80 is in use but for the purposes of getting support in the forum the flow you provide is not ideal. It would require us to install an additional contrib node.

The template node does not use javascrpt, are you thinking of the ui-template node.

Or maybe use a http request node
e.g.

[{"id":"605c596d.54259","type":"http in","z":"664244b99a502b3b","name":"","url":"/test","method":"get","upload":false,"swaggerDoc":"","x":270,"y":160,"wires":[["a309bbc2.b86bf8"]]},{"id":"a309bbc2.b86bf8","type":"http request","z":"664244b99a502b3b","name":"","method":"GET","ret":"txt","paytoqs":"ignore","url":"http://192.168.1.25:1880/response","tls":"","persist":false,"proxy":"","authType":"","x":560,"y":120,"wires":[["806968dacc5db796"]]},{"id":"088ffc4886be3459","type":"inject","z":"664244b99a502b3b","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":290,"y":200,"wires":[["a309bbc2.b86bf8"]]},{"id":"806968dacc5db796","type":"http response","z":"664244b99a502b3b","name":"httpResponse","statusCode":"","headers":{"Access-Control-Allow-Origin":"*"},"x":710,"y":240,"wires":[]},{"id":"fa8d6555.069f2","type":"http in","z":"664244b99a502b3b","name":"","url":"/response","method":"get","upload":false,"swaggerDoc":"","x":280,"y":340,"wires":[["dc5fed152c7ce697"]]},{"id":"dc5fed152c7ce697","type":"template","z":"664244b99a502b3b","name":"httpFormat","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{\n    \"credits\": \"credits\",\n    \"property\":\"property\",\n    \"final\":\"final\",\n    \"city\":\"city\",\n    \"uf\":\"uf\",\n    \"man\":\"man\",\n    \"model\":\"model\",\n    \"year\":\"year\",\n    \"cor\":\"cor\",\n    \"situation\":\"situation\"    \n}","output":"json","x":520,"y":340,"wires":[["1db96b05a975cce0","7025b429af244030"]]},{"id":"7025b429af244030","type":"debug","z":"664244b99a502b3b","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":700,"y":320,"wires":[]},{"id":"1db96b05a975cce0","type":"http response","z":"664244b99a502b3b","name":"httpResponse","statusCode":"","headers":{"Access-Control-Allow-Origin":"*"},"x":720,"y":360,"wires":[]},{"id":"6ff4d35fb0e3aec6","type":"template","z":"664244b99a502b3b","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n    <title>JSON Test</title>\n</head>\n<body>\n    <div id=\"myData\"></div>\n    <script>\n        fetch('Server URL:3100/response')\n            .then(function (response) {\n                return response.json();\n            })\n            .then(function (data) {\n                appendData(data);\n            })\n            .catch(function (err) {\n                console.log('error: ' + err);\n            });\n        function appendData(data) {\n            var mainContainer = document.getElementById(\"myData\");\n            for (var i = 0; i < data.length; i++) {\n                var div = document.createElement(\"div\");\n                div.innerHTML = 'Name: ' + data[i].credits + ' ' + data[i].marca;\n                mainContainer.appendChild(div);\n            }\n        }\n    </script>\n</body>\n</html>","output":"str","x":570,"y":180,"wires":[[]]}]

add back your http port nodes, as i do not have them installed.

Sure, the whole template content on the Get/test side is sent to the browser for execution, that part works.
The Browser then calls the Get/Response node asking for the JSON that is sent back to the browser.

The response part can be run alone as long as it has an URL. In my case if I use Chrome and call http://URL:3100/Response I get the intended JSON returned to the browser. So the response side can be independently tested and it works.

The Get/test side does not do a lot as it only provides to the browser the code it has to run, from there is it a communication Browser X Get/Response
I don't see the "node-red-contrib-http-custom-port" as doing much but who knows...

What is the result if you replace the content in your template node by something plain simple, like below ?

<html>
    <head></head>
    <body>
        <h1>Hello Forum </h1>
    </body>
</html>

Not sure what you mean, please check my last post.
It might well be a problem with the way Fetch is been implemented and the problem would be on the Browser side as it tries to execute what Get/Test sent to it.
Never used JavaScript/Fetch

So, the flow and the picture you provided in the OP are only distraction for the real point to address that is the use of fetch. It would be better that you copy and paste in the post the JavaScript code that you want to debug.

I have been trying several thing, both in browser alone and NodeRed.
I am working in both fronts. I have been trying with JavaScript forum for days and started to think it may be a problem with Node-Red so I decided to post it here as well because others may have encountered the same problem.
The Fetch syntax that I posted here is a result of days of tests and that in Browser X Apache works well but my API runs on Node-Red.

So, no distraction, I do not have any distraction for close to a week now trying to sort this problem out.

Ultimately I have to work on both fronts because I really don't know where the problem is.

On another front I am also trying to dish Fetch entirely and are also trying to work with Ajax...
Thanks

Have you used develpoer tools in your browser to see if any messages are showing up in the console or error logs?

Yes, on Microsoft Edge no messages at all.
On Chrome I get: autofill.js:10546 Uncaught TypeError: Cannot read properties of undefined (reading 'encrypt')
But it seems to come from some of their internal libraries.
The result on the browser is the same, nothing.

OK i see now, this is working for me

[{"id":"605c596d.54259","type":"http in","z":"30af2d3e.d94ea2","name":"","url":"/test","method":"get","upload":false,"swaggerDoc":"","x":210,"y":2940,"wires":[["6ff4d35fb0e3aec6"]]},{"id":"6ff4d35fb0e3aec6","type":"template","z":"30af2d3e.d94ea2","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n    <title>JSON Test</title>\n</head>\n<body>\n    <div id=\"myData\">test</div>\n    <script>\n        fetch('http://192.168.1.25:1880/response')\n            .then(function (response) {\n                return response.json();\n            })\n            .then(function (data) {\n                appendData(data);\n            })\n            .catch(function (err) {\n                console.log('error: ' + err);\n            });\n        function appendData(data) {\n            var mainContainer = document.getElementById(\"myData\");\n            \n                const div = document.createElement(\"div\");\n                div.innerHTML = 'Name: ' + data.credits + ' ' + data.city;\n                mainContainer.appendChild(div);\n            \n        }\n    </script>\n</body>\n</html>","output":"str","x":510,"y":2960,"wires":[["806968dacc5db796","dc805192.256218"]]},{"id":"088ffc4886be3459","type":"inject","z":"30af2d3e.d94ea2","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":230,"y":2980,"wires":[["6ff4d35fb0e3aec6"]]},{"id":"806968dacc5db796","type":"http response","z":"30af2d3e.d94ea2","name":"httpResponse","statusCode":"","headers":{"Access-Control-Allow-Origin":"*"},"x":650,"y":3020,"wires":[]},{"id":"dc805192.256218","type":"debug","z":"30af2d3e.d94ea2","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":720,"y":2900,"wires":[]},{"id":"fa8d6555.069f2","type":"http in","z":"30af2d3e.d94ea2","name":"","url":"/response","method":"get","upload":false,"swaggerDoc":"","x":220,"y":3120,"wires":[["dc5fed152c7ce697"]]},{"id":"dc5fed152c7ce697","type":"template","z":"30af2d3e.d94ea2","name":"httpFormat","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{\n    \"credits\": \"credits\",\n    \"property\":\"property\",\n    \"final\":\"final\",\n    \"city\":\"city\",\n    \"uf\":\"uf\",\n    \"man\":\"man\",\n    \"model\":\"model\",\n    \"year\":\"year\",\n    \"cor\":\"cor\",\n    \"situation\":\"situation\"    \n}","output":"json","x":460,"y":3120,"wires":[["1db96b05a975cce0","7025b429af244030"]]},{"id":"7025b429af244030","type":"debug","z":"30af2d3e.d94ea2","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":640,"y":3100,"wires":[]},{"id":"1db96b05a975cce0","type":"http response","z":"30af2d3e.d94ea2","name":"httpResponse","statusCode":"","headers":{"Access-Control-Allow-Origin":"*"},"x":660,"y":3140,"wires":[]}]

I removed the loop as the returned data from /response is an object.
output in browser

test

Name: credits city

Add your fetch url back in script

[edit] re pasted flow.json just incase there was an error

I am trying to run it right now, may be you pasted something missing.
I am getting: SyntaxError: Expected ',' or ']' after array element in JSON at position 3025
As I import the flow. Thanks

Extra [ at start i pasted code again in above post.

1 Like

Dear E1cid, thanks very much for your effort, I got the return piece of my JSON as you shown.
I will now transport the concept back to my main API.
Thanks a lot

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