您好,我在将参数传递给 NodeJS 的 javascript 中的对象有问题。
当我在函数内创建对象时:
var obj = {host: 123,
port: 456}
并给我一个 ws.send(obj.host) 它返回 123。
但是,当我执行以下操作时:
function a(param) {
var obj = param;
ws.send (obj.host);
}
a({host: 123, port: 456});
它返回我未定义
代码是:
var http = require("http");
var Sequelize = require("sequelize");
var mysql = require('sequelize').mysql;
var WebSocketServer = require('ws').Server;
var server = http.createServer(function(request, response) {
response.end("WS port:1337");
});
server.listen(1337, function() { });
var wss = new WebSocketServer({ server: server });
wss.on('connection', function(ws) {
ws.on('message', function(message) {
ws.send(exec(message));
});
function exec(msg) {
var cmd = msg.split(':')[0].toLowerCase(); //Get the first string before ':' and all cmd begin with 3 letters.
var message = '';
for(i=4; i<msg.length; i++) {
message += msg[i];
}
console.log("Cmd type: " + cmd);
switch(cmd) { //send 'msg:' type the message after ':'.
case 'msg' :
return message;
case 'sql' : //send to another function the object message like {host: 'x.x.x.x', port: xxxx, user...}
sql(message);
return 'res:';
break;
default:
return "not defined!";
}
}
});