Banng
Banng

Reputation: 531

Serve different instance of static page on same port in node js

I am having node.js server running on port 3000.

On this port it returns "index.html" page, this page have iframe inside it.

Depending on some conditions, we are changing iframe's source to various static html pages.

Below is the high level code and diagram

enter image description here

Now this works well when only single app is connected to node.js server using socket on http://ip_address:3000

For simplicity please consider this: App#1 emit's one event

socket.emit

upon receiving on event to server, server will emit event to page (web) index.html then the source page inside index.html will be set to different static html page.

Problem here is when app#2 or app#3 is connected to node.js server then it serve same page contents which is being shown to app#1.

What we would like achieve is : When App#1 is connected to server state of index.html should NOT be shown to app#2 when it is connected. App#2 should see initial default page assigned in index.html i.e new instance of index.html.

I am really newbie here for node.js, can anyone please share ideas and basic architecture flaw to solve this problem ?

Appreciate your patience for reading this till here !

Upvotes: 0

Views: 215

Answers (2)

O. Jones
O. Jones

Reputation: 108796

It looks like you want to serve a different version of index.html to a visitor depending on the app from which they come.

In that case you cannot serve it from a file using res.sendFile(filename). In other words, /index.html is no longer a static object, but rather an object you must render specifically for each visitor. Express is made for this: you can use

async function renderRootPage (req, res, next) {
   /* code to figure out what to put into the returned page */
   const iframePage = 'whatever.html'
   res.render( {iframePage} ).end()
}
app.get('/index.html', renderRootPage)
app.get('/', renderRootPage)

Instead, you must use a template to generate the appropriate version of index.html for the web site visitor in question. You didn't tell us which express template engine you use, so it's hard to give you more specific advice.

Upvotes: 1

AnonyMouze
AnonyMouze

Reputation: 416

by default when you start socket and connection joined, everyone will be connected to "/" namespace. Once you emit anything without specifying namespace or room, it will board cast to everyone connected to "/" namespace. That's the reason everyone gets on the same page. There are 2 ways I could think of. First is each user gets a separate room. The second is to keep track of socket id and instead use "socket.to(socketId)". you can refer to this https://socket.io/docs/v3/server-api/#socket-rooms link to check how socket.to and room work. they have good examples to start with.

Upvotes: 1

Related Questions