I am trying to send req.params to the front end and use it with various js functions, but I do not know how to access it on the client side with js.
Specifically, I am trying to grab the req.param
called namespace
that the user inputs using
app.get('/:namespace', function(req,res){
res.render('chatLayout', { title: 'Welcome to the ' +
req.params.namespace +" room!"}), {namespace: req.params.namespace };
});
and then set a variable named room
in the client side js file likes this:
var room= io.connect('http://localhost:3000/' +namespace);
However, since I do not know how to make the req.params.namespace
accessible to the client side js file, namespace is undefined.
Note: I am using pug as my templating language
I have tried a few things.
Trying to call
req.params.namespace
ornamespace
, from within the client side js file, but both throw an error saying that they are not definedCreating a global variable in the pug file using a script tag before calling the js file and setting
var a=namespace
orvar a=req.params.namespace
, but this doesn't seem to make the variable accessible to the js file. It seems like it should work like in this question Can I access variables from another file? , so maybe this method might work but I am just not doing it correctly
Backend
var express= require('express');
var socket= require('socket.io');
//App setup
var app= express();
app.set('view engine', 'pug');
var server= app.listen(3000, function(){
});
//Static files
app.get('/:namespace', function(req,res){
res.render('chatLayout', { title: 'Welcome to the ' +
req.params.namespace +" room!"}), {namespace: req.params.namespace };
});
Client side js
var room= io.connect('http://localhost:3000/' +namespace);
Pug file
doctype html
html(lang='en')
head
title= title
meta(charset='utf-8')
meta(name='viewport', content='width=device-width, initial-scale=1')
<script
src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'>
</script>
<script src="/gameChat.js"></script>
link(rel='stylesheet', href='/style.css')
body
<h1>#{title} </h1>
<div id= "chat">
<div id= "chat-window">
<div id= "output"></div>
<div id= "feedback"></div>
</div>
<form id ="form">
<input id= "handle" type= "text" placeholder="Handle"/>
<input id= "message" type = "text" placeholder="Message"/>
<button id= "send">Send</button>
</form>
</div>