JS canvas to Node JS server communication

Hello, I am trying to send some numerical values from javascript canvas to node JS server. The front-end function looks like this:

canvas.addEventListener(
        "click",
        function () {
          let data=[event.offsetX,event.offsetY];
          
          //Send data to server
          
        },
        false
      );

I want for example for the server to switch the two values in the array and send them back. However I can’t get the back-end part working. I am using the basic Glitch template for NodeJS server:

const path = require("path");

// Require the fastify framework and instantiate it
const fastify = require("fastify")({
  // set this to true for detailed logging:
  logger: false
});

// Setup our static files
fastify.register(require("fastify-static"), {
  root: path.join(__dirname, "public"),
  prefix: "/" // optional: default '/'
});

// fastify-formbody lets us parse incoming forms
fastify.register(require("fastify-formbody"));

// point-of-view is a templating manager for fastify
fastify.register(require("point-of-view"), {
  engine: {
    handlebars: require("handlebars")
  }
});

// Our main GET home page route, pulls from src/pages/index.hbs
fastify.get("/", function(request, reply) {
  // params is an object we'll pass to our handlebars template
  let params = {
    greeting: "Hello Node!"
  };
  // request.query.paramName <-- a querystring example
  reply.view("/src/pages/index.hbs", params);
});

// A POST route to handle form submissions
fastify.post("/", function(request, reply) {
  let params = {
    greeting: "Hello Form!"
  };
  // request.body.paramName <-- a form post example
  reply.view("/src/pages/index.hbs", params);
});

// Run the server and report out to the logs
fastify.listen(process.env.PORT, '0.0.0.0', function(err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
  console.log(`Your app is listening on ${address}`);
  fastify.log.info(`server listening on ${address}`);
});

Thanks a lot for any help.

it looks like you haven’t written up an attempt yet. there’s only a placeholder comment in the client code that you posted. and in the serve code you posted, I can’t tell that there’s anything meant to receive numerical values and switch them.

is there something specifically not working on the backend?

one question about the client code though: does what you have there work so far? I usually see the handler callback with an event parameter, i.e. function (event) { ... }

Thank you, you are right, I haven’t written an attempt yet. I can’t find an example of calling and handling such request. I’ve only seen examples that use HTML form to invoke request but I need the script to do it. The frontend is working fine.
Once I will have the request object at the backend, I hope I can handle it.

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