我有一个非常简单的脚本来测试读取 URL 参数。该脚本在运行节点的 2 台计算机上正确执行,但运行节点的第三台计算机失败。这是脚本:
var http = require('http');
var URL = require('url');
var host = '127.0.0.1';
var port = 8181;
// Is called when a request comes in
handler = function(req, res) {
var url_parts = URL.parse(req.url);
console.log("url_parts = "+url_parts);
var query = url_parts.query;
console.log("xxx query = "+query);
var qArray = parseGetVars(query);
var body = {
"errorCode": "0","errorMessage":"","params" : qArray
};
// sets content-type of the responce
res.writeHead(200, {
'Content-Type' : 'application/json'
});
// terminates the response, and passes back the json as text.
res.end(JSON.stringify(body));
};
var parseGetVars = function(thisString) {
var getVars = new Array();
var qString = thisString;
console.log("qString = "+qString);
if(qString!=''){
var pairs = qString.split(/\&/);
for (var i in pairs) {
var nameVal = pairs[i].split(/\=/);
getVars[nameVal[0]] = nameVal[1];
}
}
console.log("getVars = "+getVars);
return getVars;
}
http.createServer(handler).listen(port, host);
console.log('Server running at http://' + host + ':' + port + '/');
调用脚本如下: http ://mydomain.com:8181/?d=1&p=2
正如我所说,此脚本在 2 台计算机上运行良好(均运行 v0.10.7)。第三次我在控制台中收到此错误:
Server running at http://localhost:8181/
url_parts = [object Object]
xxx query = d=1&p=2
qString = d=1&p=2
getVars =
url_parts = [object Object]
xxx query = null
qString = null
/Users/me/Sites/node/params.js:36
var pairs = qString.split(/\&/);
^
TypeError: Cannot call method 'split' of null
at parseGetVars (/Users/me/Sites/node/params.js:36:23)
at Server.handler (/Users/me/Sites/node/params.js:14:15)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2027:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
at Socket.socket.ondata (http.js:1917:22)
at TCP.onread (net.js:510:27)
任何想法都非常感谢