404 Error When Fetching JSON File After Restarting Node-RED Server

I'm encountering an issue with fetching a JSON file in a Node-RED project. Here's the scenario:

Context:

I have a Node-RED setup where I serve a table.json file from the public folder.
The JSON file is accessed through a Vue.js component using the fetch method.

Issue:

When I initially start the Node-RED server, the JSON file is successfully fetched and everything works as expected.
However, after stopping and restarting the Node-RED server, I get a 404 (Not Found) error when attempting to fetch table.json.

Error Message:

The error in the console is: GET http://localhost:1880/table.json 404 (Not Found)

Current Setup:

The table.json file is located in the public directory of the Node-RED installation.

My fetch method looks like this:

    async fetchData() {
      try {
        const response = await fetch('/table.json');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        this.desserts = data.desserts;
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

Steps Taken:

  • Verified that the table.json file is in the correct directory.
  • Checked that the file path in the fetch request is accurate.
  • Ensured the server is configured to serve static files correctly.

Additional Information:

  • After restarting the server, accessing http://localhost:1880/table.json in the browser returns a 404 error.

Admin edit: Adjusted formatting for reabability.

Are you on Windows or Linux?

Can you explain why you are accessing the file through Javascript (in a function node?) rather than using the Read File node?

What definitions do you have in your settings.js file for httpStatic and httpStaticRoot?

I’m using a Linux environment for this setup.

I am accessing the JSON file through JavaScript in a Vue.js component

  1. Frontend Data Fetching:
  • The JSON file is served as a static asset and accessed directly from the client-side using the fetch method. This approach is suitable because it allows the Vue.js frontend to dynamically retrieve and display the data from the JSON file.
  1. Dynamic Updates:
  • By using the fetch method, I can ensure that the frontend always retrieves the most recent version of the JSON file without needing to restart or modify the Node-RED flow. This is useful for dynamic data that might change frequently.
  • Read file i did not study about that still please tell how to resolve my errors is there a way in read file node.

A sample flow:

[{"id":"ac8cd5b50b88add7","type":"file in","z":"713407daf1a16efe","name":"","filename":"filename","filenameType":"msg","format":"utf8","chunk":false,"sendError":false,"encoding":"none","allProps":false,"x":380,"y":140,"wires":[["8faad665da1b5139"]]},{"id":"8faad665da1b5139","type":"json","z":"713407daf1a16efe","name":"","property":"payload","action":"","pretty":false,"x":530,"y":140,"wires":[["330395ab1e5fa28b"]]},{"id":"330395ab1e5fa28b","type":"debug","z":"713407daf1a16efe","name":"File contents","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":690,"y":140,"wires":[]},{"id":"367dcd5f8ae5ae21","type":"watch","z":"713407daf1a16efe","name":"Watch /home/pi/.node-red/table.json","files":"/home/pi/.node-red/table.json","recursive":"","x":200,"y":60,"wires":[["7d4439b16fe9670a","affa322e0aa7c1f4"]]},{"id":"7d4439b16fe9670a","type":"debug","z":"713407daf1a16efe","name":"Complete msg","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":700,"y":60,"wires":[]},{"id":"affa322e0aa7c1f4","type":"switch","z":"713407daf1a16efe","name":"msg.event != remove","property":"event","propertyType":"msg","rules":[{"t":"neq","v":"remove","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":180,"y":140,"wires":[["ac8cd5b50b88add7"]]}]

The watch node will be triggered whenever the file is altered.
It passes a fair amount of info about the change as seen in the debug output.
If the file is deleted then msg.event will contain "remove". In this case the read file node would give an error so I use a switch node to ignore any file deletion.
Note that you might find it preferable to test if msg.size exists and is > 0.

The Read file node fetches the contents and the Json parser converts it to JSON.

Sample flow for to bring the table through the json data using the template node.
image

[
    {
        "id": "a9c7bea885b4a5c5",
        "type": "tab",
        "label": "Flow 2",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "54cc040a2d3ace1f",
        "type": "ui-template",
        "z": "a9c7bea885b4a5c5",
        "group": "",
        "page": "46b4eb5c828e89a7",
        "ui": "",
        "name": "",
        "order": 0,
        "width": "0",
        "height": "0",
        "head": "",
        "format": "<template>\n  <div :style=\"{ width: '80%', height: '400px', margin: '20px auto' }\">\n    <v-data-table :group-by=\"groupBy\" :headers=\"headers\" :items=\"desserts\" item-value=\"name\">\n      <template v-slot:group-header=\"{ item, columns, toggleGroup, isGroupOpen }\">\n        <tr>\n          <td :colspan=\"columns.length\">\n            <v-icon @click=\"toggleGroup(item)\" style=\"cursor: pointer;\">\n              {{ isGroupOpen(item) ? '$expand' : '$next' }}\n            </v-icon>\n            {{ item.value ? 'Contains gluten' : 'Gluten free' }}\n          </td>\n        </tr>\n      </template>\n    </v-data-table>\n  </div>\n</template>\n\n<script>\n  export default {\n    data() {\n      return {\n        groupBy: [\n          {\n            key: 'gluten',\n            order: 'asc',\n          },\n        ],\n        headers: [\n          {\n            title: 'Dessert (100g serving)',\n            align: 'start',\n            sortable: false,\n            key: 'name',\n          },\n          { title: 'Calories', key: 'calories' },\n          { title: 'Fat (g)', key: 'fat' },\n          { title: 'Carbs (g)', key: 'carbs' },\n          { title: 'Protein (g)', key: 'protein' },\n          { title: 'Iron (%)', key: 'iron' },\n        ],\n        desserts: []\n      };\n    },\n    mounted() {\n      this.fetchData();\n    },\n    methods: {\n      async fetchData() {\n        try {\n          // Fetch the JSON file from the public directory\n          const response = await fetch('/table.json');\n          \n          const data = await response.json();\n          \n            this.desserts = data.desserts;\n         \n        } catch (error) {\n          console.error('Error fetching data:', error);\n        }\n      }\n    }\n  };\n</script>",
        "storeOutMessages": true,
        "passthru": true,
        "resendOnRefresh": true,
        "templateScope": "widget:page",
        "className": "",
        "x": 360,
        "y": 200,
        "wires": [
            []
        ]
    },
    {
        "id": "f70475843b82780a",
        "type": "comment",
        "z": "a9c7bea885b4a5c5",
        "name": "client side fethch method",
        "info": "api call from the client side using the fetch method",
        "x": 370,
        "y": 160,
        "wires": []
    },
    {
        "id": "46b4eb5c828e89a7",
        "type": "ui-page",
        "name": "apicalltable",
        "ui": "627823be90657171",
        "path": "/page9",
        "icon": "home",
        "layout": "grid",
        "theme": "default",
        "order": 1,
        "className": "",
        "visible": "true",
        "disabled": "false"
    },
    {
        "id": "627823be90657171",
        "type": "ui-base",
        "name": "My Dashboard",
        "path": "/dashboard",
        "includeClientData": true,
        "acceptsClientConfig": [
            "ui-notification",
            "ui-control"
        ],
        "showPathInSidebar": false,
        "showPageTitle": true,
        "navigationStyle": "icon",
        "titleBarStyle": "default"
    }
]

here my path of my json file in node red: /node-red/packages/node_modules/@node-red/editor-client/public/table.json

while stoping the serven and run again i m getting this issue
VM1164:3
GET http://localhost:1880/table.json 404 (Not Found)
VM1164:7 Error fetching data:
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

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