nodejs中通过http、https、proxy发送请求

http

get请求

const http = require('http');

const httpOptions = {
    // 这里一定是hostname
    hostname: 'www.gov.cn',port: '80',method: 'get',path: '/',headers:{
        useragent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/100.0.4896.60 Safari/537.36'
    },}

let httpBody = '';
const httpReq = http.request(httpOptions,(res) =>{
    res.on('data',(d)=> {
        httpBody += d;
    })
    res.on('end',()=> {
        console.log(`Request by http,response data: ${httpBody}`);
    })
})
// 一定要调用end方法,否则请求一直pending,最后会让你怀疑人生
httpReq.end();

使用代理发送http请求

注意:以下方式未验证通过,但是可以通过http创建一个server,在server中解析请求,然后再通过request的方法发送实际的请求,这种方式一定可以,待续

const http = require('http');


const httpProxyOptions = {
    // host 一定要配置为代理服务器的地址
    host: '101.66.88.1',// port 一定要配置为代理服务器的端口
    port: '6666',// 不再需要配置hostname
    // hostname: 'www.baidu.com',// path 为实际要请求的地址
    path: 'http://www.gov.cn',}

let httpProxyBody = '';
const httpProxyReq = http.request(httpProxyOptions,(d)=> {
        httpProxyBody += d;
    })
    res.on('end',response data: ${httpProxyBody}`);
    })
})
httpProxyReq.end();

https

get请求

const http = require('http');

const httpsOptions = {
    hostname: 'www.baidu.com',port: '443',}

let httpsBody = '';
const httpsReq = https.request(httpsOptions,(d)=> {
        httpsBody += d;
    })
    res.on('end',response data: ${httpsBody}`);
    })
})
httpsReq.end();

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...