nodejs做代理访问的一个小示例

直接上代码

const http=require('node:http');
const url=require('node:url');
const server=http.createServer();
//你想访问的网址,可以随便更改
const domain='www.baidu.com';
server.on('request',function(req,res){
    let url_parts=url.parse(req.url);
    let options={
        host:domain,
        port:80,
        path:url_parts.pathname+(url_parts.search||''),
        headers:{'Host':domain,'User-Agent':req.headers['user-agent']},//这里必须要user-agent表示代理访问
        method:req.method   //访问的模式,Post,get,put等
    };
    //这里必须是http.request()请求访问,不能用http.get()
    const creq=http.request(options,function(cres){
        res.writeHead(cres.statusCode,cres.headers);
        cres.pipe(res);
    });
   //利用pipe管道返回数据
    req.pipe(creq);

});
server.listen(1337,'localhost');
server.on('listening',function(){
    console.log('服务端开始监听');
})
server.on('connection',function(socket){
    console.log('代理客户端已建立连接');
});
server.on('error',function(e){
    if(e.code==="EADDRINUSE")
    {
        console.log('服务端口被占用');
        return;
    }
    console.log('服务端出错,错误代码为'+e.code);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值