Send data from custom node node.js script to html/browser?

Hi, I'm writing a custom node plugin and I would like to display in the HTML form page some data that's available in the node.js side of the script. I can't really understand how to do that and I can't find any documentation, could someone point me in the right direction please?

To give some context, I'm generating a setup code and I need to display it on the Node-RED ui to allow the user to use it.

You have a couple of choices. Of which the "official" approach would be to create an API end-point on the admin instance of ExpressJS that is exposed to your runtime code on RED.httpAdmin. You can attach a new endpoint (or an ExpressJS router with its own endpoints) to that which will return the data you need. You call it from within the JavaScript of your html file.

The core serial node has a simple example. For more complex examples, you can wade through the uibuilder code. All of the web processing in uibuilder starts from the UibWeb class in libs/web.js.

Thanks for the help!

@TotallyInformation I'm getting a Cannot GET /my-path (404 error) when I register the endpoint with:

 RED.httpAdmin.use(
    '/my-path/:id',
    function (req, res) {
      res.send({ hello: "World!");
    }
  );

Do you have any suggestion? I also tried httpAdmin.get

I'm fetching it with

      $.getJSON('my-path/123', function (data) {
        console.log(data);
      });

And I see it correctly (?) calls http://127.0.0.1:1880/my-path

Edit it seems to be a problem with params (:/foo), if I use query arguments it works :man_shrugging:

Should work I think. if you manually set the url in the browser to http://127.0.0.1:1880/my-path/abc, does that work?

You probably want to use RED.httpAdmin.get rather than use, just so it is clear you only ever want to use a GET on that endpoint.

I always use query arguments on GET REST API's. If I need something more complex, I'll use POST with a body containing JSON. You should always use POST if needing to send anything sensitive (and use HTTPS of course). I have a helper function that puts all parameters no matter what form they come in into a standard object.

Nope, not working, so weird. Not a big deal but it's the first time I see Express act like this.

Just make sure that whatever base URL path you chose, it won't ever clash with anything else (so don't use a common word for example).

For uibuilder, everything starts with /uibuilder/...

I used my package name as scope so it should be good.

1 Like

Any reason you chose use instead of a specific verb?

Here is a working example.

@Steve-Mcl as I mentioned I also tried with .get.

For now I got it working with a query parameter so I'll leave it as is, thanks for the help though!

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