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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM