node.js模拟正向代理proxy

/*
 * @Description: proxy-模拟正向代理
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-11-01 12:18:22
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-11-01 17:34:51
 */

const http = require("http")
const url = require("url")
const { createProxyMiddleware } = require("http-proxy-middleware")

const server = http.createServer((req, res) => {
    const urlStr = req.url;
    if (/\/proxy/.test(urlStr)) {
        const proxy = createProxyMiddleware('/proxy', {
            target: 'http://mobile.pinduoduo.com',
            changeOrigin: true
        })
        console.log("111");
        proxy(req, res)
    }else if(/\api/.test(urlStr)){
        const proxy2 = createProxyMiddleware('/api',{
            target:"https://gate.lagou.com",
            changeOrigin:true,
            pathRewrite:{
                '^/api':''
            }
        })
        console.log("222");
        proxy2(req,res)
    }else{
        console.log("error");
        
    }
})

server.listen(5080, () => {
    console.log('localhost:5080 Listen...');
})

 

可以看到 当我们访问  http://localhost:5080/api时

 

加上资源地址

 

posted @ 2021-11-01 20:40  南柯Dream丶  阅读(371)  评论(0)    收藏  举报