Getting HTTP headers with Node.js

后端 未结 6 2013
野的像风
野的像风 2020-11-29 02:36

Is there a built in way to get the headers of a specific address via node.js?

something like,

var headers = getUrlHeaders(\"http://stackoverflow.com\         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 03:16

    I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

    HEAD

    Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


    Something like this, based it on this question:

    var cli = require('cli');
    var http = require('http');
    var url = require('url');
    
    cli.parse();
    
    cli.main(function(args, opts) {
            this.debug(args[0]);
    
            var siteUrl = url.parse(args[0]);
            var site = http.createClient(80, siteUrl.host);
            console.log(siteUrl);
    
            var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
            request.end();
    
            request.on('response', function(response) {
                    response.setEncoding('utf8');
                    console.log('STATUS: ' + response.statusCode);
                    response.on('data', function(chunk) {
                            console.log("DATA: " + chunk);
                    });
            });
    });
    

提交回复
热议问题