【NodeJS】發送 https 請求

HttpsClient.js   模塊

const https = require('https');
// 不需要 body 的請求
const noBodyReqs = ['head','get','copy','purge','unlock'];
// 可能需要 body 的請求
const hasBodyReqs = ['post','put','patch','delete','options','link','unlink','lock','propfind','view'];

const HttpsClient = {};

noBodyReqs.concat(hasBodyReqs).forEach(method => {
    HttpsClient[method] = obj => {
        return new Promise(function (cb) {
            const options = {
                host: obj.host,
                port: 443,
                path: obj.path,
                method,
                headers: obj.headers ? obj.headers : {},
            };
            const req = https.request(options, res => {
                let chunks = Buffer.from([]);
                let chunksLength = chunks.length;
                res.on('data', chunk => {
                    chunks = Buffer.concat([chunks,chunk],chunksLength + chunk.length);
                    chunksLength = chunks.length;
                });
                res.on('end', () => {
                    cb(chunks.toString());
                });
            });

            req.on('error', e => {console.log(`request error: ${e}`);});

            if(hasBodyReqs.indexOf(method) !== -1) req.write(obj.body);
            req.end();
        });
    }
});

module.exports = HttpsClient;

 

index.js   使用

const HttpsClient = require('../HttpsClient');

HttpsClient.get({
    host: 'www.deepbrainchain.vip',
    path: '/Home/Index',
}).then(data => {
    console.log(data);
});

HttpsClient.post({
    host: 'www.deepbrainchain.vip',
    path: '/Home/PostTest',
    headers: {'content-type': 'text'},
    body: 'asssd'
}).then(data => {
    console.log(data);
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章