I can't understand why I am getting error: on next code:
void logout(HTTPServerRequest req, HTTPServerResponse res)
{
try
{
logInfo("Logout section");
Json request = req.json;
Json responseBody = Json.emptyObject; //
if (req.session) // if user have active session
{
res.terminateSession();
responseBody["status"] = "success";
responseBody["isAuthorized"] = false;
res.writeJsonBody(responseBody);
logInfo("-------------------------------------------------------------------------------");
logInfo(responseBody.toString);
logInfo("^-----------------------------------------------------------------------------^");
logInfo("User %s logout", request["username"]); //
logInfo("User 12333333333333 logout"); //
}
else
{
responseBody["status"] = "fail"; // user do not have active session?
logInfo("User do not have active session");
res.writeJsonBody(responseBody);
}
writeln("-------before-------");
writeln(responseBody.toString);
res.writeJsonBody(responseBody);
writeln("-------after-------");
}
catch (Exception e)
{
logInfo(e.msg);
writeln("3333");
}
}
Here is screenshot
What I am doing wrong?
writeJsonBody serializes the response JSON at once, sets the status
and content_type
and also closes the output stream. Have a close look at your code - it calls res.writeJsonBody(responseBody)
twice.
If you want to stream a response, you could access the output stream like this res.bodyWriter.put("a sentence.")
, but please note that once this has been accessed for the first time, it is not allowed to change any header (e.g. status code) of the response because the headers have been sent to client.
Btw you might be interest in Vibed's high-level REST API feature.