如何在Node.js中动态更改值?

时间:2014-12-17 16:35:04

标签: node.js dynamic chat

我正在开发Node.js中的基本聊天功能。所以,我有用户列表列表,通过点击每个索引我可以得到唯一的值,这将帮助我做私人客户端 - 服务器聊天。但我无法弄清楚如何更改 app.js 文件中的值。

Node.js代码

app.js

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
num = "1";

  app.set('view engine', 'ejs');    
  server.listen(4000);

        app.get('/', function(req, res){
             //res.sendfile(__dirname + '/index.html');
             res.render(__dirname + '/index.html', { num: num });
       });

        io.sockets.on('connection', function(socket){

           socket.on('send message'+num, function(data){
               io.sockets.emit('new message'+num, data);
        }); 

 });

的index.html

<body>
<div id="chat"></div>
<form id="send-message">
    <input size="35" id="message"></input>
    <input type="submit"></input>
</form>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
    jQuery(function($){
        var socket = io.connect();

        var $messageForm = $('#send-message');
        var $messageBox = $('#message');
        var $chat = $('#chat');
        var msg = $('#message').val();
        var num = "1";

        $messageForm.submit(function(e){
            e.preventDefault();

            socket.emit('send message'+num, $messageBox.val());
            $messageBox.val('');
        });

        socket.on('new message'+num, function(data){
            $chat.append(data + "<br/>");
        });
    });
</script>

错误

TypeError: Property 'engine' of object #<View> is not a function
at View.render (C:\node_demo\chat\node_modules\express\lib\view.js:76:8)
at Function.app.render (C:\node_demo\chat\node_modules\express\lib\application.js:506:10)
at ServerResponse.res.render (C:\node_demo\chat\node_modules\express\lib\response.js:756:7)
at C:\node_demo\chat\app.js:16:6
at callbacks (C:\node_demo\chat\node_modules\express\lib\router\index.js:161:37)
at param (C:\node_demo\chat\node_modules\express\lib\router\index.js:135:11)
at pass (C:\node_demo\chat\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\node_demo\chat\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\node_demo\chat\node_modules\express\lib\router\index.js:33:10)
at next (C:\node_demo\chat\node_modules\express\node_modules\connect\lib\proto.js:190:15)

我可以在index.html中动态更改“num”变量,但我无法找到如何在 app.js 文件中执行相同操作。如何将值传递给app.js文件。

请告诉我,建议我一些好的解决方案。

1 个答案:

答案 0 :(得分:2)

使用模板。对于ejs,您只需:

  • npm install ejs
  • app.set('view engine', 'ejs');
  • res.sendfile(__dirname + '/index.html');更改为res.render(__dirname + '/index.html', { num: num });
  • 然后在index.html更改var num = "1";var num = "<%= num %>";