我有以下代码,用于通过TCP捕获JSON数据,然后根据JSON文件中的内容创建新路由。所以如果我的一个JSON文件有:
{"pagename": "singsong"}
然后我希望我的路由为mywebsite:8000/singsong
并包含来自singsong
页面名称的所有数据。
我面临的问题是我的TCP数据被发送到所有路由。因此,当我尝试为每个数据创建新路由时,我的路由mywebsite:8000/singsong
将包含{"pagename": "hazel"}
的JSON数据。
我的代码原样:
server.on("connection", function(socket){
chunk = "";
socket.on('data', function(data){
chunk += data.toString(); // Add string on the end of the variable 'chunk'
d_index = chunk.indexOf(';'); // Find the delimiter
// While loop to keep going until no delimiter can be found
while (d_index > -1) {
try {
string = chunk.substring(0,d_index); // Create string up until the delimiter
json = JSON.parse(string); // Parse the current string
app.set('fee', data);
app.set('dee', json);
console.log(json.pagename); // Function that does something with the current chunk of valid json.
app.get("/"+json.pagename, function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(req.app.get('dee')));
res.end();
});
}
catch(e){
console.log(e);
}
chunk = chunk.substring(d_index+1); // Cuts off the processed chunk
d_index = chunk.indexOf(';'); // Find the new delimiter
}
});
socket.on("close", function(){
console.log("connection closed");
});
});
答案 0 :(得分:1)
这是一个捕获闭包变量(用let
定义)中每个特定请求的json的示例,而不是使用app.set()
使每个请求发生冲突,因为它们尝试使用相同的存储位置:
server.on("connection", function(socket) {
let chunk = "";
socket.on('data', function(data) {
chunk += data.toString(); // Add string on the end of the variable 'chunk'
let d_index = chunk.indexOf(';'); // Find the delimiter
// While loop to keep going until no delimiter can be found
while (d_index > -1) {
try {
let string = chunk.substring(0, d_index); // Create string up until the delimiter
// define local variables that can be used in a closure
let json = JSON.parse(string); // Parse the current string
let localData = data;
console.log(json.pagename); // Function that does something with the current chunk of valid json.
app.get("/" + json.pagename, function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write(JSON.stringify(json));
res.end();
});
} catch (e) {
console.log(e);
}
chunk = chunk.substring(d_index + 1); // Cuts off the processed chunk
d_index = chunk.indexOf(';'); // Find the new delimiter
}
});
socket.on("close", function() {
console.log("connection closed");
});
});
另外,请注意我使用let
定义所有变量,因此它们在函数内部的范围正确,而不是意外的全局变量,这可能会产生难以发现的错误。