【发布时间】:2019-09-22 07:08:32
【问题描述】:
我正在尝试将req.params发送到前端并与各种js函数一起使用,但我不知道如何在客户端使用js访问它。
具体来说,我正在尝试获取用户输入使用的名为namespace 的req.param
app.get('/:namespace', function(req,res){
res.render('chatLayout', { title: 'Welcome to the ' +
req.params.namespace +" room!"}), {namespace: req.params.namespace };
});
然后在客户端js文件中设置一个名为room的变量,如下所示:
var room= io.connect('http://localhost:3000/' +namespace);
但是,由于我不知道如何使客户端 js 文件可以访问 req.params.namespace,因此未定义命名空间。
注意:我使用 pug 作为我的模板语言
我已经尝试了一些东西。
尝试从客户端 js 文件中调用
req.params.namespace或namespace,但都抛出错误,提示它们未定义在调用js文件并设置
var a=namespace或var a=req.params.namespace之前使用脚本标签在pug文件中创建一个全局变量,但这似乎并没有使js文件可以访问该变量。看起来它应该像这个问题 Can I access variables from another file? 那样工作,所以也许这种方法可能有效,但我只是做得不对
后台
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 };
});
客户端js
var room= io.connect('http://localhost:3000/' +namespace);
哈巴狗文件
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>
【问题讨论】: