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',
    method: 'get',
    // path 为实际要请求的地址
    path: 'http://www.gov.cn',
    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 httpProxyBody = '';
const httpProxyReq = http.request(httpProxyOptions, (res) =>{
    res.on('data', (d)=> {
        httpProxyBody += d;
    })
    res.on('end', ()=> {
        console.log(`Request by http, response data: ${httpProxyBody}`);
    })
})
httpProxyReq.end();

https

get请求

const http = require('http');

const httpsOptions = {
    hostname: 'www.baidu.com',
    port: '443',
    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 httpsBody = '';
const httpsReq = https.request(httpsOptions, (res) =>{
    res.on('data', (d)=> {
        httpsBody += d;
    })
    res.on('end', ()=> {
        console.log(`Request by http, response data: ${httpsBody}`);
    })
})
httpsReq.end();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值