Node.js/http

来自康健生活
Kangkk​(留言 | 贡献)2022年4月21日 (四) 07:16的版本 (创建页面,内容为“== 标题文字 == == 示例 == <syntaxhighlight lang="javascript"> const https = require('https'); function formatResData(data, headers) { const type = headers['c…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

标题文字

示例

const https = require('https');
function formatResData(data, headers) {
  const type = headers['content-type'];
  if (!type || type?.indexOf('application/json') !== -1) {
    if (typeof data === 'string') {
      try {
        data = JSON.parse(data);
      } catch (e) { /* Ignore */ }
    }
  }
  return data;
}
// 封装get请求
function get(url, headers = {}) {
  return new Promise((resolve, reject) => {
    const req = https.get(url, { headers }, res => {
      let had = false;
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        had = true;
        res.data = formatResData(chunk, res.headers);
        resolve(res);
      });
      res.on('end', () => {
        if (had) return;
        resolve(res);
      });
    });
    req.on('error', e => {
      reject(e);
    });
  }).catch(e => {
    throw new Error(e || 'Request error');
  });
}
// 封装POST请求
function post(url, data, headers = {}) {
  return new Promise((resolve, reject) => {
    const req = https.request(url, { method: 'POST', headers }, res => {
      let had = false;
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        had = true;
        res.data = formatResData(chunk, res.headers);
        resolve(res);
      });
      res.on('end', () => {
        if (had) return;
        resolve(res);
      });
    });
    req.on('error', e => {
      reject(e);
    });
    // 写入请求的数据
    data && req.write(JSON.stringify({data}));
    req.end();
  }).catch(e => {
    throw new Error(e || 'Request error');
  });
}
module.exports = {
  get,
  post
};