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
});
}