由于某种原因,我似乎无法全神贯注,每当我Object
通过网络发送时,它的参数都会从我Object
通过网络从服务器发送到我在客户端读回它时发生变化。
这是场景:
我正在测试一个 API 以从数据库中删除您的用户帐户。您以特殊格式发送authToken
和参数,服务器查询数据库,如果找到,您的用户帐户将被删除。当一切正常时,您的帐户,服务器会将此字符串发回给您:username
Object
{ header: { type: 'success' }, body: {} }
这被称为平原SuccessEnvelope
。但是,当我从服务器读取返回的字符串时,我得到了这个:
{ header: { type: 'error' }, body: {} }
现在,似乎type
参数正在某处更改,但我不知道在哪里!您将在下面找到处理所有这些请求的相关代码:
服务器.js
server = net.createServer(function(socket) {
socket.on("data", function(data) {
try {
// Accept Envelope from client
var input = new Envelope(data.toString());
if (input.verify()) { // Make sure client Envelope has correct data
switch (input.header.type) { // Route commands based on Envelope "type"
case "user":
userHandler.parseEnvelope(input, function(err, res) {
if (err) {
socket.write(errors.parseError(err).toString());
} else {
socket.write(res.toString());
}
});
break;
default:
socket.write(new Envelope().toString());
break;
}
} else {
socket.write(errors.parseError(
new errors.MissingHeaderDataError()).toString());
}
} catch (err) {
socket.write(errors.parseError(err).toString());
}
});
});
用户处理程序.js
// removing some of the unnecessary stuff
case "delete":
// Make sure user provided all necessary information.
if (!header.token || !body.username) {
return callback(new errors.MissingEnvelopeDataError("Missing the 'token' and/or
'username' parameter(s) in header and/or body, respectively"));
} else {
// Delete the user's account. So sad to see them go... :'(
User.findOne({"token": header.token, "username": body.username}, "+token +_id",
function(err, user) {
if (err) {
return callback(err);
} else {
user.remove(function(err) {
if (err) {
return callback(err);
} else {
// Everything went according to plan. Return a SuccessEnvelope to the user.
callback(new SuccessEnvelope());
}
});
}
});
}
break;
谁能看到我做错了什么?任何帮助都会很棒。提前致谢!
编辑:包含我的测试用例可能也是一个好主意......
deleteUser = {
"header": {
"type": "user",
"method": "delete",
"token": ""
},
"body": {
"username": ""
}
}
describe("Delete user", function() {
it("should return a MissingEnvelopeDataError when deleting a user without a token or
username", function(done) {
connection.write(JSON.stringify(deleteUser));
connection.on("data", function(res) {
res = JSON.parse(res.toString());
res.header.should.have.property("type", "error");
res.header.should.have.property("errorType", "MissingEnvelopeDataError");
done();
});
});
it("should return a SuccessEnvelope when deleting a user", function(done) {
deleteUser.header.token = user.token;
deleteUser.body.username = user.username;
connection.write(JSON.stringify(deleteUser));
connection.on("data", function(res) {
res = JSON.parse(res.toString());
console.dir(res);
res.header.should.have.property("type", "success");
// res.body.should.be.empty
(function() {
if (Object.keys(res.body).length == 0) {
return true;
} else {
return false;
}
})();
done();
});
});
});
您在此处看到的user
变量只是一个简单的对象,它存储了所有用户信息。