zoukankan      html  css  js  c++  java
  • Node.js(1) http和https模块发送HTTP(S)请求

    https

    HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module.
    HTTPS是基于TLS/SSL的HTTP协议。在Node.js中,这是作为一个单独的模块实现的。

    https作为客户端使用时,与http一样具有相同的接口:request(): http.ClientRequest

    example

    判断URL是否支持范围请求

    import * as http from 'http';
    import * as https from 'https';
    import { URL } from 'url';
    
    /**
     * 判断url是否支持范围请求
     * @param url 
     */
    function isSupportedRange(url: URL | string): Promise<boolean> {
        return new Promise((resolve, reject) => {
            if (typeof url === 'string') url = new URL(url);
            const options: http.RequestOptions = {
                method: 'HEAD',
                headers: {
                    'Range': 'bytes=0-',
                },
            };
            let req: http.ClientRequest; // 根据URL协议,判断使用http还是https模块发送请求
            function callback(response: http.IncomingMessage) {
                // console.log(response.statusCode);
                // console.log(response.headers);
                // 假如在响应中存在 Accept-Ranges 首部(并且它的值不为 “none”),那么表示该服务器支持范围请求。
                if (response.statusCode === 206 || (response.headers["accept-ranges"] && response.headers["accept-ranges"] !== 'none')) resolve(true);
                resolve(false);
            }
            switch (url.protocol) {
                case 'http:': {
                    req = http.request(url, options, callback);
                    break;
                }
                case 'https:': {
                    req = https.request(url, options, callback);
                    break;
                }
                default: return void resolve(false);
            }
            req.addListener('error', (err: Error) => {
                reject(err); // 请求失败
            });
            req.end(); // refresh request stream
        });
    }
    

    END

  • 相关阅读:
    第2课 有符号与无符号
    第1课 基本数据类型
    HDU 5821 Ball
    Codeforces Round #228 (Div. 2) C. Fox and Box Accumulation
    HDU 5810 Balls and Boxes
    HDU 5818 Joint Stacks
    HDU 5813 Elegant Construction
    Codeforces Round #357 (Div. 2)C. Heap Operations
    Codeforces Round #364 (Div. 2) C. They Are Everywhere
    HDU5806 NanoApe Loves Sequence Ⅱ
  • 原文地址:https://www.cnblogs.com/develon/p/13936591.html
Copyright © 2011-2022 走看看