亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > JavaScript > 正文

Node.js原生api搭建web服務器的方法步驟

2019-11-19 12:08:10
字體:
來源:轉載
供稿:網友

node.js 實現一個簡單的 web 服務器還是比較簡單的,以前利用 express 框架實現過『nodeJS搭一個簡單的(代理)web服務器』。代碼量很少,可是使用時需要安裝依賴,多處使用難免有點不方便。于是便有了完全使用原生 api 來重寫的想法,也當作一次 node.js 復習。

1、靜態 web 服務器

'use strict'  const http = require('http') const url = require('url') const fs = require('fs') const path = require('path') const cp = require('child_process')  const port = 8080 const hostname = 'localhost'  // 創建 http 服務 let httpServer = http.createServer(processStatic) // 設置監聽端口 httpServer.listen(port, hostname, () => {   console.log(`app is running at port:${port}`)   console.log(`url: http://${hostname}:${port}`)  cp.exec(`explorer http://${hostname}:${port}`, () => {}) }) // 處理靜態資源 function processStatic(req, res) {   const mime = {   css: 'text/css',   gif: 'image/gif',   html: 'text/html',   ico: 'image/x-icon',   jpeg: 'image/jpeg',   jpg: 'image/jpeg',   js: 'text/javascript',   json: 'application/json',   pdf: 'application/pdf',   png: 'image/png',   svg: 'image/svg+xml',   woff: 'application/x-font-woff',   woff2: 'application/x-font-woff',   swf: 'application/x-shockwave-flash',   tiff: 'image/tiff',   txt: 'text/plain',   wav: 'audio/x-wav',   wma: 'audio/x-ms-wma',   wmv: 'video/x-ms-wmv',   xml: 'text/xml'  }   const requestUrl = req.url   let pathName = url.parse(requestUrl).pathname   // 中文亂碼處理  pathName = decodeURI(pathName)   let ext = path.extname(pathName)   // 特殊 url 處理  if (!pathName.endsWith('/') && ext === '' && !requestUrl.includes('?')) {   pathName += '/'   const redirect = `http://${req.headers.host}${pathName}`   redirectUrl(redirect, res)  }   // 解釋 url 對應的資源文件路徑  let filePath = path.resolve(__dirname + pathName)   // 設置 mime  ext = ext ? ext.slice(1) : 'unknown'  const contentType = mime[ext] || 'text/plain'   // 處理資源文件  fs.stat(filePath, (err, stats) => {     if (err) {    res.writeHead(404, { 'content-type': 'text/html;charset=utf-8' })    res.end('<h1>404 Not Found</h1>')       return   }     // 處理文件   if (stats.isFile()) {    readFile(filePath, contentType, res)   }     // 處理目錄   if (stats.isDirectory()) {       let html = "<head><meta charset = 'utf-8'/></head><body><ul>"    // 遍歷文件目錄,以超鏈接返回,方便用戶選擇    fs.readdir(filePath, (err, files) => {         if (err) {      res.writeHead(500, { 'content-type': contentType })      res.end('<h1>500 Server Error</h1>')      return     } else {           for (let file of files) {             if (file === 'index.html') {               const redirect = `http://${req.headers.host}${pathName}index.html`        redirectUrl(redirect, res)       }       html += `<li><a href='${file}'>${file}</a></li>`      }      html += '</ul></body>'      res.writeHead(200, { 'content-type': 'text/html' })      res.end(html)     }    })   }  }) } // 重定向處理 function redirectUrl(url, res) {  url = encodeURI(url)  res.writeHead(302, {   location: url  })  res.end() } // 文件讀取 function readFile(filePath, contentType, res) {  res.writeHead(200, { 'content-type': contentType })  const stream = fs.createReadStream(filePath)  stream.on('error', function() {   res.writeHead(500, { 'content-type': contentType })   res.end('<h1>500 Server Error</h1>')  })  stream.pipe(res) } 

2、代理功能

// 代理列表 const proxyTable = {  '/api': {   target: 'http://127.0.0.1:8090/api',   changeOrigin: true  } } // 處理代理列表 function processProxy(req, res) {   const requestUrl = req.url   const proxy = Object.keys(proxyTable)   let not_found = true  for (let index = 0; index < proxy.length; index++) {      const k = proxy[index]      const i = requestUrl.indexOf(k)      if (i >= 0) {     not_found = false     const element = proxyTable[k]        const newUrl = element.target + requestUrl.slice(i + k.length)        if (requestUrl !== newUrl) {         const u = url.parse(newUrl, true)          const options = {       hostname : u.hostname,       port   : u.port || 80,       path   : u.path,          method  : req.method,       headers : req.headers,       timeout : 6000      }          if(element.changeOrigin){       options.headers['host'] = u.hostname + ':' + ( u.port || 80)      }          const request = http      .request(options, response => {             // cookie 處理       if(element.changeOrigin && response.headers['set-cookie']){        response.headers['set-cookie'] = getHeaderOverride(response.headers['set-cookie'])       }       res.writeHead(response.statusCode, response.headers)       response.pipe(res)      })      .on('error', err => {            res.statusCode = 503       res.end()      })     req.pipe(request)    }       break   }  }   return not_found } function getHeaderOverride(value){   if (Array.isArray(value)) {      for (var i = 0; i < value.length; i++ ) {    value[i] = replaceDomain(value[i])   }  } else {   value = replaceDomain(value)  }   return value } function replaceDomain(value) {   return value.replace(/domain=[a-z.]*;/,'domain=.localhost;').replace(/secure/, '') } 

3、完整版

服務器接收到 http 請求,首先處理代理列表 proxyTable,然后再處理靜態資源。雖然這里面只有二個步驟,但如果按照先后順序編碼,這種方式顯然不夠靈活,不利于以后功能的擴展。koa 框架的中間件就是一個很好的解決方案。完整代碼如下:

'use strict'  const http = require('http') const url = require('url') const fs = require('fs') const path = require('path') const cp = require('child_process') // 處理靜態資源 function processStatic(req, res) {   const mime = {   css: 'text/css',   gif: 'image/gif',   html: 'text/html',   ico: 'image/x-icon',   jpeg: 'image/jpeg',   jpg: 'image/jpeg',   js: 'text/javascript',   json: 'application/json',   pdf: 'application/pdf',   png: 'image/png',   svg: 'image/svg+xml',   woff: 'application/x-font-woff',   woff2: 'application/x-font-woff',   swf: 'application/x-shockwave-flash',   tiff: 'image/tiff',   txt: 'text/plain',   wav: 'audio/x-wav',   wma: 'audio/x-ms-wma',   wmv: 'video/x-ms-wmv',   xml: 'text/xml'  }   const requestUrl = req.url   let pathName = url.parse(requestUrl).pathname   // 中文亂碼處理  pathName = decodeURI(pathName)   let ext = path.extname(pathName)   // 特殊 url 處理  if (!pathName.endsWith('/') && ext === '' && !requestUrl.includes('?')) {   pathName += '/'   const redirect = `http://${req.headers.host}${pathName}`   redirectUrl(redirect, res)  }   // 解釋 url 對應的資源文件路徑  let filePath = path.resolve(__dirname + pathName)   // 設置 mime  ext = ext ? ext.slice(1) : 'unknown'  const contentType = mime[ext] || 'text/plain'   // 處理資源文件  fs.stat(filePath, (err, stats) => {     if (err) {    res.writeHead(404, { 'content-type': 'text/html;charset=utf-8' })    res.end('<h1>404 Not Found</h1>')       return   }  // 處理文件   if (stats.isFile()) {    readFile(filePath, contentType, res)   }  // 處理目錄   if (stats.isDirectory()) {       let html = "<head><meta charset = 'utf-8'/></head><body><ul>"    // 遍歷文件目錄,以超鏈接返回,方便用戶選擇    fs.readdir(filePath, (err, files) => {         if (err) {      res.writeHead(500, { 'content-type': contentType })      res.end('<h1>500 Server Error</h1>')      return     } else {           for (let file of files) {             if (file === 'index.html') {              const redirect = `http://${req.headers.host}${pathName}index.html`        redirectUrl(redirect, res)       }       html += `<li><a href='${file}'>${file}</a></li>`      }      html += '</ul></body>'      res.writeHead(200, { 'content-type': 'text/html' })      res.end(html)     }    })   }  }) } // 重定向處理 function redirectUrl(url, res) {  url = encodeURI(url)  res.writeHead(302, {   location: url  })  res.end() } // 文件讀取 function readFile(filePath, contentType, res) {  res.writeHead(200, { 'content-type': contentType })  const stream = fs.createReadStream(filePath)  stream.on('error', function() {   res.writeHead(500, { 'content-type': contentType })   res.end('<h1>500 Server Error</h1>')  })  stream.pipe(res) } // 處理代理列表 function processProxy(req, res) {  const requestUrl = req.url  const proxy = Object.keys(proxyTable)  let not_found = true  for (let index = 0; index < proxy.length; index++) {     const k = proxy[index]     const i = requestUrl.indexOf(k)     if (i >= 0) {    not_found = false    const element = proxyTable[k]    const newUrl = element.target + requestUrl.slice(i + k.length)     if (requestUrl !== newUrl) {     const u = url.parse(newUrl, true)     const options = {      hostname : u.hostname,      port   : u.port || 80,      path   : u.path,         method  : req.method,      headers : req.headers,      timeout : 6000     };     if(element.changeOrigin){      options.headers['host'] = u.hostname + ':' + ( u.port || 80)     }     const request =      http.request(options, response => {               // cookie 處理       if(element.changeOrigin && response.headers['set-cookie']){        response.headers['set-cookie'] = getHeaderOverride(response.headers['set-cookie'])       }       res.writeHead(response.statusCode, response.headers)       response.pipe(res)      })      .on('error', err => {       res.statusCode = 503       res.end()      })     req.pipe(request)    }    break   }  }  return not_found } function getHeaderOverride(value){  if (Array.isArray(value)) {    for (var i = 0; i < value.length; i++ ) {          value[i] = replaceDomain(value[i])    }  } else {    value = replaceDomain(value)  }  return value} function replaceDomain(value) {  return value.replace(/domain=[a-z.]*;/,'domain=.localhost;').replace(/secure/, '') } function compose (middleware) {  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')   for (const fn of middleware) {     if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')  }   return function (context, next) {   // 記錄上一次執行中間件的位置     let index = -1   return dispatch(0)    function dispatch (i) {    // 理論上 i 會大于 index,因為每次執行一次都會把 i遞增,    // 如果相等或者小于,則說明next()執行了多次      if (i <= index) return Promise.reject(new Error('next() called multiple times'))       index = i    let fn = middleware[i]       if (i === middleware.length) fn = next    if (!fn) return Promise.resolve()      try {        return Promise.resolve(fn(context, function next () {        return dispatch(i + 1)     }))    } catch (err) {          return Promise.reject(err)    }   }  } } function Router(){   this.middleware = [] } Router.prototype.use = function (fn){   if (typeof fn !== 'function') throw new TypeError('middleware must be a function!')  this.middleware.push(fn)  return this} Router.prototype.callback= function() {   const fn = compose(this.middleware)   const handleRequest = (req, res) => {   const ctx = {req, res}   return this.handleRequest(ctx, fn)  }  return handleRequest } Router.prototype.handleRequest= function(ctx, fn) {  fn(ctx) }  // 代理列表 const proxyTable = {  '/api': {   target: 'http://127.0.0.1:8090/api',   changeOrigin: true  } }  const port = 8080 const hostname = 'localhost' const appRouter = new Router()  // 使用中間件 appRouter.use(async(ctx,next)=>{  if(processProxy(ctx.req, ctx.res)){   next()  } }).use(async(ctx)=>{  processStatic(ctx.req, ctx.res) })  // 創建 http 服務 let httpServer = http.createServer(appRouter.callback())  // 設置監聽端口 httpServer.listen(port, hostname, () => {  console.log(`app is running at port:${port}`)  console.log(`url: http://${hostname}:${port}`)  cp.exec(`explorer http://${hostname}:${port}`, () => {}) }) 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
亚洲精品国产精品国产自| 92裸体在线视频网站| 亚洲欧洲日本专区| 久久国产精品久久精品| 日韩欧美精品网址| 97精品免费视频| 免费97视频在线精品国自产拍| 亚洲人成啪啪网站| 国产成人免费av电影| 97av视频在线| www.亚洲成人| 国产精品一区久久| 性欧美xxxx视频在线观看| 日韩美女在线观看一区| 中文字幕在线看视频国产欧美| 国产精品黄页免费高清在线观看| 亚洲品质视频自拍网| 久久久久久97| 久久久精品中文字幕| 精品视频—区二区三区免费| 欧美激情国产高清| 欧美亚洲国产视频| 亚洲人永久免费| 欧美性猛交xxxx免费看久久久| 久久久久久久国产精品视频| 91在线无精精品一区二区| 欧美国产在线视频| 777午夜精品福利在线观看| 亚洲精品福利资源站| 精品久久国产精品| 7777kkkk成人观看| 91在线播放国产| 一区二区三区久久精品| 久久免费视频在线观看| 欧美丝袜一区二区三区| 亚洲国产欧美自拍| 欧美一级高清免费播放| 夜夜嗨av一区二区三区免费区| 日韩在线观看免费| 国产精品啪视频| 成人午夜两性视频| 欧美国产乱视频| 91精品国产综合久久久久久久久| 色偷偷av亚洲男人的天堂| 久久久精品中文字幕| 51精品国产黑色丝袜高跟鞋| 欧洲成人午夜免费大片| 超碰97人人做人人爱少妇| 91av在线免费观看| 91在线国产电影| 欧美性猛交xxxx黑人猛交| 国产成人在线亚洲欧美| 亚洲成人亚洲激情| 欧美日韩色婷婷| 亚洲第一国产精品| 久久久久久18| 欧美寡妇偷汉性猛交| 在线观看中文字幕亚洲| 久久久精品久久| 欧美极品美女视频网站在线观看免费| 久久精品国产一区二区电影| 国产亚洲精品综合一区91| 韩国欧美亚洲国产| 亚洲91av视频| 成人国产精品免费视频| 69av视频在线播放| 高清在线视频日韩欧美| 国产精品视频色| 欧美激情一区二区三区在线视频观看| 亚洲国产精品人久久电影| 久久久久久久一区二区三区| 欧美日韩免费区域视频在线观看| 91亚洲精品在线观看| 国产精品青草久久久久福利99| 欧美诱惑福利视频| 2021久久精品国产99国产精品| 欧美另类99xxxxx| 97国产精品免费视频| 中文字幕在线看视频国产欧美| 欧美黑人一区二区三区| 亚洲一级一级97网| 精品日本高清在线播放| 亚洲色图35p| 亚洲欧洲黄色网| 中文字幕亚洲欧美日韩在线不卡| 成人中心免费视频| 在线视频国产日韩| 97成人超碰免| 91中文精品字幕在线视频| 中国人与牲禽动交精品| 亚洲一区制服诱惑| 久久成人av网站| 欧美激情一区二区三级高清视频| 九九热精品视频在线播放| 91超碰中文字幕久久精品| 久久精品视频99| 国产亚洲欧美视频| 欧美亚洲视频在线观看| 亚洲欧洲日韩国产| 国产精品91久久久| 欧美在线一区二区视频| 国产精品国内视频| 久热在线中文字幕色999舞| 性色av一区二区三区红粉影视| 俺去了亚洲欧美日韩| 国产美女91呻吟求| 国产精品99久久久久久人| 琪琪第一精品导航| 欧美小视频在线| 成人av在线网址| 一区二区成人精品| 精品久久久国产精品999| 97av视频在线| 另类少妇人与禽zozz0性伦| 91久久国产精品| 亚洲最大的网站| 欧美精品九九久久| 久久精品91久久久久久再现| 日韩av综合中文字幕| 日韩久久免费电影| 国产91精品久久久久| 欧美黑人巨大xxx极品| 欧美精品18videosex性欧美| 欧美激情啊啊啊| 久久中文久久字幕| 亚洲黄色www| 欧美激情va永久在线播放| 欧洲午夜精品久久久| 亚洲一区二区中文字幕| 蜜臀久久99精品久久久无需会员| 日韩精品福利在线| 俺也去精品视频在线观看| 岛国视频午夜一区免费在线观看| 欧美日韩国产在线| 91美女片黄在线观看游戏| 黄色成人在线播放| 91精品视频大全| 欧美日韩午夜剧场| 国产精品精品久久久| 国产亚洲精品久久久优势| 欧美国产日韩xxxxx| 国产精品女视频| 国产精品91在线| 欧美激情成人在线视频| 麻豆精品精华液| 精品中文字幕在线2019| 精品无码久久久久久国产| 日韩毛片在线观看| 琪琪亚洲精品午夜在线| 亚洲一区二区免费在线| 久久精品国产99国产精品澳门| 欧美人与性动交| 日韩精品视频在线观看网址| 国产欧美日韩综合精品| 亚洲一区二区三区sesese| 精品亚洲国产视频| 国产一区二区三区精品久久久| 国产精品视频导航| 欧美激情小视频| 亚洲精品福利视频| 国产91在线高潮白浆在线观看| 国产精品久久久久久久7电影| 国产精品av在线播放| 国产亚洲精品美女久久久|