使用桥接获取PhantomJS返回的状态代码

我正在创build一个小API来监视我的一些站点的性能。 为此我需要加载时间和http状态码。 我使用节点js和phatomjs来做到这一点,到目前为止我的加载时间恰到好处,但我似乎无法得到状态代码。 我尝试了一些不同的东西,但没有一个工作到目前为止。

这是我现在的代码:

var express = require('express'); var app = express(); app.get('/', function(req, res) { res.type('application/json'); res.send('{"status": "running"}'); }); app.get('/site/:url', function(req, res){ res.type('application/json'); res.header('Access-Control-Allow-Origin', '*'); res.header('Cache-Control', 'no-cache'); var url = decodeURIComponent(req.param('url')); var phantom = require('phantom'); var time, code; phantom.create(function(ph){ ph.createPage(function(page){ time = Date.now(); page.open(url, function(status){ time = Date.now() - time; res.send({"status": status, "time": time}); }); }); }); }); var server = app.listen(80, function() { var host = server.address().address; var port = server.address().port; console.log('Got\'cha .. ', host, port); }); 

我已经尝试http://phantomjs.org/api/webpage/handler/on-resource-received.html,但我似乎无法看到我可以调用它的位置,所以我可以将其与其他数据一起返回。 到目前为止,我得到了这样的{"status":"success","time":1723}

有人知道我能做什么吗?

你是对的, onResourceReceived提供了实际的状态码。 如function细节所示,您必须使用page.set设置事件处理程序。

你可以假定在页面opencallback之前执行onResourceReceived

 var statusCode = null; page.set('onResourceReceived', function(resource){ statusCode = resource.status; }); page.open(url, function(status){ time = Date.now() - time; res.send({"status": statusCode, "time": time}); }); 

如果你不能确定(你应该做一些testing),那么你可以使用像这样waitFor

 var statusCode = null; page.set('onResourceReceived', function(resource){ statusCode = resource.status; }); page.open(url, function(status){ waitFor(function(){ return !!statusCode; }, function(){ time = Date.now() - time; res.send({"status": statusCode, "time": time}); }); });