I am using server.listen(...)
from PhantomJS. I understand that it is largely experimental and should not be used in production. I use it for a simple screenshot server that accepts generates screenshots for the URL; This is a toy project that I use to play with PhantomJS. I noticed a problem with long queries, in particular where the response
object is not available. Here are the relevant snippets from my code:
var service = server.listen(8080, function (request, response) { response.statusCode = 200; if (loglevel === level.VERBOSE) { log(request); } else { console.log("Incoming request with querystring:", request.url); } var params = parseQueryString(request.url); if (params[screenshotOptions.ACTION] === action.SCREENSHOT) { getScreenshot(params, function (screenshot) { response.headers["success"] = screenshot.success; //<-- here is where I get the error that response.headers is unavailable. Execution pretty much stops at that point for that particular request. response.headers["message"] = screenshot.message; if (screenshot.success) { response.write(screenshot.base64); } else { response.write("<html><body>There were errors!<br /><br />"); response.write(screenshot.message.replace(/\n/g, "<br />")); response.write("</body></html>"); } response.close(); }); } else { response.write("<html><body><h1>Welcome to the screenshot server!</h1></body></html>") response.close(); } });
getScreenshot
is an asynchronous method that uses the WebPage.open(...)
function to open a web page; this function is also asynchronous. So it seems that when the callback passed as an argument to getScreenshot
is finally called, it seems that the response
object has already been deleted. I basically get the following error from PhantomJS:
Error: cannot access member `headers' of deleted QObject
I believe this is due to the fact that the request expires, and therefore the connection is closed. The documentation mentions calling response.write("")
at least once to make sure the connection remains open. I tried calling response.write("")
at the beginning of server.listen(...)
, and I even tried a pretty hacky solution where I used setInterval(...)
to execute response.write("")
every 500 milliseconds ( I even lowered it to 50). I also took care to clear the interval as soon as I finished. However, I still seem to get this problem.
Is this something I will have to face until they make the webserver module more reliable? Or is there a way around this?
source share