加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

Node.js 原生 api 搭建 web 服务器

发布时间:2019-02-16 07:08:45 所属栏目:业界 来源:想不起来了
导读:node.js 实现一个简单的 web 服务器还是比较简单的,以前利用 express 框架实现过『nodeJS搭一个简单的(代理)web服务器』。代码量很少,可是使用时需要安装依赖,多处使用难免有点不方便。于是便有了完全使用原生 api 来重写的想法,也当作一次 node.js 复

2、代理功能

  1. // 代理列表 
  2. const proxyTable = { 
  3.   '/api': { 
  4.     target: 'http://127.0.0.1:8090/api', 
  5.     changeOrigin: true 
  6.   } 
  7. // 处理代理列表 
  8. function processProxy(req, res) {   
  9.   const requestUrl = req.url   
  10.   const proxy = Object.keys(proxyTable)   
  11.   let not_found = true 
  12.   for (let index = 0; index < proxy.length; index++) {     
  13.       const k = proxy[index]     
  14.       const i = requestUrl.indexOf(k)     
  15.       if (i >= 0) { 
  16.         not_found = false 
  17.         const element = proxyTable[k]       
  18.         const newUrl = element.target + requestUrl.slice(i + k.length)       
  19.         if (requestUrl !== newUrl) {        
  20.           const u = url.parse(newUrl, true)         
  21.           const options = { 
  22.             hostname : u.hostname,  
  23.             port     : u.port || 80, 
  24.             path     : u.path,        
  25.             method   : req.method, 
  26.             headers  : req.headers, 
  27.             timeout  : 6000 
  28.           }         
  29.           if(element.changeOrigin){ 
  30.             options.headers['host'] = u.hostname + ':' + ( u.port || 80) 
  31.           }         
  32.           const request = http 
  33.           .request(options, response => {             
  34.             // cookie 处理 
  35.             if(element.changeOrigin && response.headers['set-cookie']){ 
  36.               response.headers['set-cookie'] = getHeaderOverride(response.headers['set-cookie']) 
  37.             } 
  38.             res.writeHead(response.statusCode, response.headers) 
  39.             response.pipe(res) 
  40.           }) 
  41.           .on('error', err => {            
  42.             res.statusCode = 503 
  43.             res.end() 
  44.           }) 
  45.         req.pipe(request) 
  46.       }       
  47.       break 
  48.     } 
  49.   }   
  50.   return not_found 
  51. function getHeaderOverride(value){   
  52.   if (Array.isArray(value)) {       
  53.    for (var i = 0; i < value.length; i++ ) { 
  54.      value[i] = replaceDomain(value[i]) 
  55.    } 
  56.   } else { 
  57.     value = replaceDomain(value) 
  58.   }   
  59.   return value 
  60. function replaceDomain(value) {   
  61.   return value.replace(/domain=[a-z.]*;/,'domain=.localhost;').replace(/secure/, '') 

3、完整版

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读