将用户名从客户端传递到服务器端[Node.js / Socket.io / JavaScript]

时间:2017-06-01 14:10:08

标签: javascript node.js socket.io

我正在尝试将用户名添加到我正在使用 node.js socket.io

目前,身份验证部分是通过 passport 完成的,它会将用户重定向到信息中心。现在用户可以点击进入世界,这将把他重定向到 enter.handlebars 网站。

所以我以下列方式渲染网站:

// Get Site
router.get('/enter', ensureAuthenticated, function(req, res){
    res.render('enter', {username: req.user.username});
});

如您所见,我将用户名传递给客户端代码,可以通过输入以下来访问:

{{username}}

但我也需要在 app.js 文件(服务器端代码)中使用此值。 我怎样才能将用户名代码中的用户名传递给服务器端代码?

问题:有没有办法,用套接字本身传递它?所以我可以在这里获得用户名?

Player.onConnect = function(socket)

我当前的 enter.handlebars 文件代码:

<body class="layout-boxed login-cover">
    <!-- Main navbar -->
    <div class="navbar navbar-inverse">
        <div class="navbar-boxed">
            <div class="navbar-header">
                <a class="navbar-brand" href="index.html"><img src="/images/logo_light.png" alt=""></a>

                <ul class="nav navbar-nav visible-xs-block">
                    <li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
                </ul>
            </div>

            <div class="navbar-collapse collapse" id="navbar-mobile">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Support</a></li>

                    <li>
                        <a href="#">
                            <i class="icon-cog3"></i>
                            <span class="visible-xs-inline-block position-right">Icon link</span>
                        </a>                        
                    </li>

                    <li class="dropdown dropdown-user">
                        <a class="dropdown-toggle" data-toggle="dropdown">
                            <span>{{username}}</span>
                            <i class="caret"></i>
                        </a>

                        <ul class="dropdown-menu dropdown-menu-right">
                            <li><a href="#"><i class="icon-user-plus"></i> My profile</a></li>
                            <li><a href="#"><i class="icon-coins"></i> My balance</a></li>
                            <li class="divider"></li>
                            <li><a href="#"><i class="icon-cog5"></i> Account settings</a></li>
                            <li><a href="../authenticate.php"><i class="icon-switch2"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /main navbar -->

    <!-- Second navbar -->
    <div class="navbar navbar-default" id="navbar-second">
        <div class="navbar-boxed">
            <ul class="nav navbar-nav no-border visible-xs-block">
                <li><a class="text-center collapsed" data-toggle="collapse" data-target="#navbar-second-toggle"><i class="icon-menu7"></i></a></li>
            </ul>

            <div class="navbar-collapse collapse" id="navbar-second-toggle">
                <ul class="nav navbar-nav">
                    <li><a href="/zworld/dashboard"><i class="icon-display4 position-left"></i> Dashboard</a></li>
                    <li class="active"><a href=""><i class="icon-heart6 position-left"></i> Enter World</a></li>
                    <li><a href=""><i class="icon-user-tie position-left"></i> Wardrobe</a></li>
                    <li><a href=""><i class="icon-price-tag position-left"></i> Store</a></li>
                    <li><a href=""><i class="icon-cart2 position-left"></i> Shop</a></li>
                </ul>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="icon-cash3 position-left"></i> 0 Zbucks</a></li>
                    <li><a href="#"><i class="icon-credit-card2 position-left"></i> 0 Zcard</a></li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /second navbar -->

    <!-- Page container -->
    <div class="page-container">


    <div class="breadcrumb-line breadcrumb-line-component content-group-lg">
                    <ul class="breadcrumb">
                        <li><a href="#"><i class="icon-home2 position-left"></i> Zworld</a></li>
                        <li class="active">Enter World</li>
                    </ul>

                    <ul class="breadcrumb-elements">
                        <li><a href="#"><i class="icon-comment-discussion position-left"></i> Private Messages</a></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                <i class="icon-gear position-left"></i>
                                Actions
                                <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu dropdown-menu-right">
                                <li><a href="#"><i class="icon-inbox pull-right"></i> Action</a></li>
                                <li><a href="#"><i class="icon-googleplus5 pull-right"></i> Another action</a></li>
                                <li><a href="#"><i class="icon-grid-alt pull-right"></i> Something else</a></li>
                                <li class="divider"></li>
                                <li><a href="#"><i class="icon-spinner2 spinner pull-right"></i> One more line</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>

        <!-- Page content -->
        <div class="page-content">

            <div id="chatModal" class="panel panel-default chatModal">
                <div class="panel-heading">
                    <h6 class="panel-title">Zworld Chat</h6>
                    <div class="heading-elements">
                        <ul class="icons-list">
                            <li><a data-action="collapse"></a></li>
                            <li><a data-action="reload"></a></li>
                        </ul>
                    </div>
                </div>

                <div style="overflow-y: scroll; position:relative; height: 200px;" class="panel-body" id="chat-text"></div>
            </div>

            <!-- Main content -->
            <div class="content-wrapper cnt">
                <div class="panel panel-flat" style="height: 700px;">
                    <canvas style="background-color: #eee;" id="ctx"></canvas>

                    <div id="chat" style="width: 100%; height: 46px; background-color: #fff; border-top: 1px solid #ddd; margin-top: -6px;">
                        <div id="subBar_left" style="float:left; width: 80%;">
                            <form id="chat-form">
                                <input id="chat-input" type="text" style="width:100%; padding-left: 10px; height: 46px; border: none;" placeholder="Enter message..." autocomplete="off"></input>
                            </form> 
                        </div>
                        <div class="verticalLine" id="subBar_right" style="float:right; width: 20%; line-height: 46px;">
                            <a class="showChat" style="color: #333333 !important; padding-left: 25px;" data-popup="tooltip" title="Open chatbox" data-placement="bottom">
                                <i class="icon-bubbles10"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Open friendlist" data-placement="bottom">
                                <i class="icon-users"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Open Map" data-placement="bottom">
                                <i class="icon-location4"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Visit room" data-placement="bottom">
                                <i class="icon-home5"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Report user" data-placement="bottom">
                                <i class="icon-flag3"></i>
                            </a>
                        </div>
                    </div>

                </div>
            </div>
            <!-- /content area -->

        </div>
        <!-- /page content -->

    </div>
    <!-- /page container -->

    <!-- Footer -->
    <div class="footer footer-boxed text-muted">
        © 2017 pr0b.com
    </div>
    <!-- /footer -->

    <script>
        var socket = io();

        // Chat
        var chatText = document.getElementById("chat-text");
        var chatInput = document.getElementById("chat-input");
        var chatForm = document.getElementById("chat-form");

        $('.showChat').click(function()
        {
            if ($('#chatModal').css('display') == 'none'){
                $('#chatModal').show();
                $('#chatModal').draggable();
            }
            else
            {
                $('#chatModal').hide();
            }   
        });

        // Game
        var Img = {};
        Img.player = new Image();
        Img.player.src = '/images/avtest.png';
        Img.map = new Image();
        Img.map.src = '/images/room.png';

        var ctx = document.getElementById("ctx").getContext("2d");
        ctx.canvas.width  = 1156;
        ctx.canvas.height = 650;

        var Player = function(initPack){
            var self = {};
            self.id = initPack.id;
            self.number = initPack.number;
            self.x = initPack.x;
            self.y = initPack.y;
            self.username = initPack.username;

            self.draw = function()
            {
                var width = Img.player.width / 1.5;
                var height = Img.player.height / 1.5;

                ctx.drawImage(Img.player, 0, 0, Img.player.width, Img.player.height, self.x, self.y, width, height)
            }

            Player.list[self.id] = self;

            return self;
        }
        Player.list = {};


        var selfId = null;

        socket.on('init', function(data){
            if(data.selfId){
                selfId = data.selfId;
            }
            for(var i = 0; i < data.player.length; i++){
                new Player(data.player[i]);
            }
        });

        socket.on('update', function(data){
            for(var i = 0; i < data.player.length; i++){
                var pack = data.player[i];
                var p = Player.list[pack.id];
                if(p){
                    if(pack.x !== undefined){
                        p.x = pack.x;
                    }
                    if(pack.y !== undefined){
                        p.y = pack.y;
                    }
                }
            }
        });

        socket.on('remove', function(data){
            for(var i = 0; i < data.player.length; i++){
                delete Player.list[data.player[i]];
            }
        });

        setInterval(function(){
            if(!selfId){
                return;
            }else{
                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                drawMap();
                for(var i in Player.list){
                    Player.list[i].draw();
                }
            }
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            drawMap();
            for(var i in Player.list){
                Player.list[i].draw();
            }
        }, 10);

        var drawMap = function(){
            ctx.drawImage(Img.map, 0, 0, ctx.canvas.width, ctx.canvas.height);
        }

        socket.on('addToChat', function(data)
        {
            chatText.innerHTML += '<div>' + data + '</div>';
        });

        chatForm.onsubmit = function(e){
            e.preventDefault();
            socket.emit('sendMsgToServer', chatInput.value);
            chatInput.value = '';
        }

        document.onkeydown = function(event)
        {
            if(event.keyCode === 68)
            {
                socket.emit('keyPress', {inputId: 'right', state: true});
            }
            else if(event.keyCode === 83)
            {
                socket.emit('keyPress', {inputId: 'down', state: true});
            }
            else if(event.keyCode === 65)
            {
                socket.emit('keyPress', {inputId: 'left', state: true});
            }
            else if(event.keyCode === 87)
            {
                socket.emit('keyPress', {inputId: 'up', state: true});
            }
        }

        document.onkeyup = function(event)
        {
            if(event.keyCode === 68)
            {
                socket.emit('keyPress', {inputId: 'right', state: false});
            }
            else if(event.keyCode === 83)
            {
                socket.emit('keyPress', {inputId: 'down', state: false});
            }
            else if(event.keyCode === 65)
            {
                socket.emit('keyPress', {inputId: 'left', state: false});
            }
            else if(event.keyCode === 87)
            {
                socket.emit('keyPress', {inputId: 'up', state: false});
            }
        }

        document.oncontextmenu = function(){
            event.preventDefault();
        }
    </script>
</body>

我当前的 app.js 文件代码:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local'), Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/zworld');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');
var zworld = require('./routes/zworld');

// Init App
var app = express();

// Socket stuff

var serv = require('http').Server(app);

var SOCKET_LIST = [];

var Entity = function(param){
    var self = {
        x: 100,
        y: 100,
        spdX: 0,
        spdY: 0,
        id: ""
    };

    if(param){
        if(param.x){
            self.x = param.x;
        }
        if(param.y){
            self.y = param.y;
        }
        if(param.id){
            self.id = param.id;
        }
    }

    self.update = function(){
        self.updatePosition();
    };

    self.updatePosition = function(){
        self.x += self.spdX;
        self.y += self.spdY;
    };

    return self;
};

var Player = function(param){
        var self = Entity(param);
        self.number = "" + Math.floor(10 * Math.random());
        self.pressingRight = false;
        self.pressingLeft = false;
        self.pressingUp = false;
        self.pressingDown = false;
        self.maxSpd = 5;
        self.username = param.username;

        var super_update = self.update;
        self.update = function(){
            self.updateSpd();
            super_update();
        };

        self.updateSpd = function()
        {
            if(self.pressingRight)
            {
                self.spdX = self.maxSpd;
            }
            else if(self.pressingLeft)
            {
                self.spdX = -self.maxSpd;
            }
            else
            {
                self.spdX = 0;
            }

            if(self.pressingUp)
            {
                self.spdY = -self.maxSpd;
            }
            else if(self.pressingDown)
            {
                self.spdY = self.maxSpd;
            }
            else
            {
                self.spdY = 0;
            }
        };

        self.getInitPack = function(){
            return {
                id:self.id,
                x:self.x,
                y:self.y,
                number:self.number
            };
        };

        self.getUpdatePack = function(){
            return {
                id:self.id,
                x:self.x,
                y:self.y,
                number:self.number
            };
        };

        Player.list[self.id] = self;

        initPack.player.push(self.getInitPack());

        return self;
};

Player.list = {};
Player.onConnect = function(socket){
    var player = Player({
        id: socket.id,
        username: socket.id
    });

    socket.on('keyPress', function(data){
        if(data.inputId === 'left')
        {
            player.pressingLeft = data.state;
        }
        else if(data.inputId === 'right')
        {
            player.pressingRight = data.state;
        }
        else if(data.inputId === 'up')
        {
            player.pressingUp = data.state;
        }
        else if(data.inputId === 'down')
        {
            player.pressingDown = data.state;
        }
    });

    var players = [];

    for(var i in Player.list){
        if(i){
            players.push(Player.list[i].getInitPack());
        }
    }

    socket.emit('init', {
        selfId: socket.id,
        player: Player.getAllInitPack()
    });
};

Player.getAllInitPack = function(){
    var players = [];

    for(var i in Player.list){
        if(i){
            players.push(Player.list[i].getInitPack());
        }
    }

    return players;
};

Player.onDisconnect = function(socket){
    delete Player.list[socket.id];
    removePack.player.push(socket.id);
};

Player.update = function(){
    var pack = [];

    for(var i in Player.list){
        if(i){
            var player = Player.list[i];
            player.update();

            pack.push(player.getUpdatePack());
        }
    }

    return pack;
};

var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    SOCKET_LIST[socket.id] = socket;

    Player.onConnect(socket);

    socket.on('disconnect', function(){
        delete SOCKET_LIST[socket.id];
        Player.onDisconnect(socket);
    });

    socket.on('sendMsgToServer', function(data){
        var playerName = ("" + socket.username).slice(2,7);
        for(var i in SOCKET_LIST)
        {
            if(i){
                SOCKET_LIST[i].emit('addToChat', playerName + ': ' + data);
            }
        }
    });

});

var initPack = {player:[]};
var removePack = {player:[]};

setInterval(function(){
    var pack = {
        player:Player.update()
    };

    for(var i in SOCKET_LIST){
        if(i){
            var socket = SOCKET_LIST[i];
            socket.emit('init', initPack);
            socket.emit('update', pack);
            socket.emit('remove', removePack);
        }
    }
    initPack.player = [];
    removePack.player = [];
}, 1000/60);

// Socket stuff end

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

// BodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

// Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Express Session
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

// Passport Init
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
    errorFormatter: function(param, msg, value){
        var namespace = param.split('.'),
        root = namespace.shift(),
        formParam = root;

        while(namespace.length){
            formParam += '[' + namespace.shift() + ']';
        }

        return{
            param : formParam,
            msg : msg,
            value : value
        };
    }
}));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (req, res, next){
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
});

app.use('/', routes);
app.use('/users', users);
app.use('/zworld', zworld);

// Set Port
app.set('port', (process.env.PORT || 3000));

serv.listen(app.get('port'), function(){
    console.log('Server started on port ' + app.get('port'));
});

1 个答案:

答案 0 :(得分:0)

如果我理解你的例子,我不确定。

对我而言,由于用户对象已附加到请求对象,因此您的用户名 已经在服务器端。

附录2017年6月2日

好的,所以,如果我理解正确,你会尝试通过http-GET将值传递给服务器。有两种方法可以做到这一点。作为路线的一部分或作为查询字符串的一部分。

因此,在您的情况下,如果您只想传递用户名,则需要像这样定义路线:

'/enter/:username'

我的用户名是例如&#39;棕榈酒&#39;然后请求看起来像

'/enter/toddy'

然后通过params对象获取用户名:

res.render(&#39;输入&#39;,req.params.username)

或者您可以使用查询字符串:

'/enter?username=toddy'

并使用

获取它
req.query.username

但是,如果用户名来自,那么你应该使用http-POST方法而不是像:

router.post('/enter', ensureAuthenticated, function(req, res){
    res.render('enter', {username: req.body.username});
});

如果使用post,数据将在正文中传递。因此,您通过提取

来检索用户名
req.body.username