【javaScript】通过http-proxy-middware引发正反向代理的思考

739 阅读1分钟

结论

正向代理隐藏真实客户端,反向代理隐藏真实服务端

  • 正向代理

v2-922c89b735165f9f47db025bd77941c2_720w.png

  • 反向代理

v2-bf5255d84d73d10500cb9c717fac8b02_720w.png

  • 使用http-proxy-middware实现正向代理达到跨域的目的
const http = require('http')
const proxy = require('http-proxy-middleware')

http.createServer((req, res) => {
  let url = req.url

  res.writeHead(200, {
    'Access-Control-Allow-Origin': '*'
  })//使用CORS解决前端页面跨域到该8080port

 /*
 1、api:是一个暗号,进行代理
 2、pathRewrite:取消api的路径,实现的功能:
     无pathRewrite:localhost:8080/api/path ==>m.lagou.com/api/path
     有pathRewrite:localhost:8080/api/path ==>m.lagou.com/path
 */
  if (/^/api/.test(url)) { 
    let apiProxy = proxy('/api', { 
      target: 'https://m.lagou.com',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    })

    // http-proy-middleware 在Node.js中使用的方法
    apiProxy(req, res)
  } else {
    switch (url) {
      case '/index.html':
        res.end('index.html')
        break
      case '/search.html':
        res.end('search.html')
        break
      default:
        res.end('[404]page not found.')
    }
  }
}).listen(8080)