nodejs http request

2 篇文章 0 订阅
2 篇文章 0 订阅

ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ(对自己真实,才不会被别人欺诈。——莎士比亚)
ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ在这里插入图片描述

const http = require('http');
const https = require('https');

const request = async (url, method, data = {}, options = {}) => {
  const pro = async () => {
    // 处理http或https
    let sender = http;
    if (url.includes('https')) {
      sender = https;
    }
    // 针对不同的请求方式做不同的处理
    if (['get'].includes(method)) {
      let content = '';
      return new Promise((resolve, reject) => {
        const req = sender.request(url, options, (res) => {
          res.setEncoding('utf8');
          res.on('data', (chunk) => {
            content += chunk;
          });
          res.on('end', () => {
            return resolve(content);
          });
        });
        req.on('error', (e) => {
          return reject(e.message);
        });
        req.end();
      })

    }
    if (['post', 'put', 'patch'].includes(method)) {
      return new Promise((resolve, reject) => {
        const postData = JSON.stringify(data);
        options = {
          method,
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
          },
          ...options
        };
        let content = '';
        const req = sender.request(url, options, (res) => {
          res.setEncoding('utf8');
          res.on('data', (chunk) => {
            content += chunk;
          });
          res.on('end', () => {
            return resolve(content);
          });
        });
        req.on('error', (e) => {
          return reject(e.message);
        });
        req.write(postData);
        req.end();
      });
    }
    throw new Error('request method invalid!');
  };
  const result = await pro();
  console.log('result-----', result);
  return {
    data: result
  };
}

request('http://www.baidu.com', 'get', {}, {});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值