如何从page.open发出的请求中查看HTTP状态代码? [英] How can I see the HTTP status code from the request made by page.open?

查看:154
本文介绍了如何从page.open发出的请求中查看HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个phantomJS脚本,其中包含以下内容:

I have a phantomJS script that contains the following:

page.open(url, function (status) {
    if (status === "fail") { /* handle failure */ }
});

状态检查有时可以工作,但是即使请求返回500,状态仍然为成功".如何获得实际的请求状态代码?

The status check works sometimes, but the status will still be "success" even if the request returns 500. How can I get the actual request status code?

推荐答案

您可以执行以下操作:

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页面),则应将其视为resources[0].status中返回的第一个请求.在 onResourceReceived 处理程序中,您可以为尝试从中获取HTTP代码的资源添加更多过滤器.

So, if you need to check the status of the first browser's request (in this case google's html page) you should see it as the first one returned in resources[0].status. In onResourceReceived handler you can add more filters for resources you try to get http code from.

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

UPDATE: thanks to @fotijr, added a check for completed responses

这篇关于如何从page.open发出的请求中查看HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆