phantomjs – 如何从page.open请求中查看HTTP状态代码?

我有一个phantomJS脚本,其中包含以下内容
page.open(url,function (status) {
    if (status === "fail") { /* handle failure */ }
});

状态检查有时会起作用,但即使请求返回500,状态仍将是“成功”.如何获取实际的请求状态代码

解决方法

你可以这样做:
var page = require('webpage').create(),system = require('system'),resources = [];

page.open('http://google.com',function (status) {
    console.log('Loaded with http status:',resources[0].status);
    phantom.exit();
});

page.onResourceReceived = function(response) {
    // check if the resource is done downloading 
    if (response.stage !== "end") return;
    // apply resource filter if needed:
    if (response.headers.filter(function(header) {
        if (header.name == 'Content-Type' && header.value.indexOf('text/html') == 0) {
            return true;
        }
        return false;
    }).length > 0)
        resources.push(response);
};

因此,如果您需要检查第一个浏览器请求的状态(在本例中为google的html页面),您应该将其视为资源[0] .status中返回的第一个请求.在onResourceReceived处理程序中,您可以为尝试从中获取http代码的资源添加更多过滤器.

更新:感谢@fotijr,添加了对已完成回复的检查

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...