I am an ASP.NET dev and I want to explore nodejs/express. In ASP.NET you can control raw html from the backend. I want to have a button click toggle the visibility of a div. I know you can do this on the frontend but is there anyways to do this on server side?
This is my code so far
const e = require('express');
var express = require('express');
const path = require('path');
var date;
//var http = require('http');
//var proxiedHttp = require('findhit-proxywrap').proxy(https);
var app = express();
var filePath = '';
app.get('/', function (req, res) {
// send records as a response
console.log(req);
filePath = path.resolve(__dirname, 'index.html');
res.sendFile(filePath);
});
2
Answers
You can achieve the server-side control of a div’s visibility in Node.js and Express by using a templating engine like EJS and defining an endpoint to handle the toggle action.
views
(this is proper convention when using ejs). Inside it, create a file calledindex.ejs
. An example of it looks something like this:You can normally just use a variable to control visibility, and send a response based on this variable’s value. However, assuming you want to manage this per-client, you’ll want to use a piece of middleware called
express-session
, which helps you individualize your users.npm install express-session
The visibility of the div is stored in the session, so it’s unique to each client. If one client toggles the div, it won’t affect other clients.
Sidenote: Writing this post has made me reflect upon the javascript everywhere paradigm.
Switching visibility of a div based on a server-side button click can be a bit different in Node.js/Express compared to ASP.NET, as Node.js is more geared towards handling dynamic interactions on the client side. However, you can achieve a similar effect by mixing server and client-side scripting.
Here’s a high-level approach using your Express app:
Render Initial State: When the user first loads the page, you can render the HTML with the desired initial visibility state of the div.
Client-Side Interaction: On the client side, use JavaScript (front-end) to handle the button click and toggle the div’s visibility. This keeps the user experience smooth and responsive.
Server Communication: If you need to perform some server-side logic when the button is clicked, you can make an AJAX request to your Express server. This request can trigger server-side actions and send back data if needed.
So, while the actual visibility toggling happens on the client side, you can still interact with the server through AJAX to trigger server-side actions when necessary.
Feel free to mix in templating engines like EJS or Pug to make rendering dynamic content in Express even smoother.