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

Get status code returned with PhantomJS using a bridge

本文关键字:返回 状态 代码 PhantomJS 网桥 获取      更新时间:2023-09-26

我正在创建一个小的 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提供了实际的状态代码。如功能详细信息所示,您必须使用 page.set 设置事件处理程序。

您可以假设onResourceReceived在页面open回调之前执行:

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});
});

如果你不能确定(你应该做一些测试),那么你可以使用类似 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});
    });
});