国产99久久精品_欧美日本韩国一区二区_激情小说综合网_欧美一级二级视频_午夜av电影_日本久久精品视频

最新文章專題視頻專題問(wèn)答1問(wèn)答10問(wèn)答100問(wèn)答1000問(wèn)答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問(wèn)答文章1 問(wèn)答文章501 問(wèn)答文章1001 問(wèn)答文章1501 問(wèn)答文章2001 問(wèn)答文章2501 問(wèn)答文章3001 問(wèn)答文章3501 問(wèn)答文章4001 問(wèn)答文章4501 問(wèn)答文章5001 問(wèn)答文章5501 問(wèn)答文章6001 問(wèn)答文章6501 問(wèn)答文章7001 問(wèn)答文章7501 問(wèn)答文章8001 問(wèn)答文章8501 問(wèn)答文章9001 問(wèn)答文章9501
當(dāng)前位置: 首頁(yè) - 科技 - 知識(shí)百科 - 正文

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

來(lái)源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 22:01:03
文檔

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

Node.js原生api搭建web服務(wù)器的方法步驟:node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.j
推薦度:
導(dǎo)讀Node.js原生api搭建web服務(wù)器的方法步驟:node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.j

node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.js 復(fù)習(xí)。

1、靜態(tài) web 服務(wù)器

'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' 
 
// 創(chuàng)建 http 服務(wù) 
let httpServer = http.createServer(processStatic) 
// 設(shè)置監(jiān)聽(tīng)端口 
httpServer.listen(port, hostname, () => { 
 console.log(`app is running at port:${port}`) 
 console.log(`url: http://${hostname}:${port}`) 
 cp.exec(`explorer http://${hostname}:${port}`, () => {}) 
}) 
// 處理靜態(tài)資源 
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 對(duì)應(yīng)的資源文件路徑 
 let filePath = path.resolve(__dirname + pathName) 
 // 設(shè)置 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、完整版

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

'use strict' 
 
const http = require('http') 
const url = require('url') 
const fs = require('fs') 
const path = require('path') 
const cp = require('child_process') 
// 處理靜態(tài)資源 
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 對(duì)應(yīng)的資源文件路徑 
 let filePath = path.resolve(__dirname + pathName) 
 // 設(shè)置 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) { 
 // 記錄上一次執(zhí)行中間件的位置 
 let index = -1 
 return dispatch(0) 
 function dispatch (i) { 
 // 理論上 i 會(huì)大于 index,因?yàn)槊看螆?zhí)行一次都會(huì)把 i遞增, 
 // 如果相等或者小于,則說(shuō)明next()執(zhí)行了多次 
 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) 
}) 
 
// 創(chuàng)建 http 服務(wù) 
let httpServer = http.createServer(appRouter.callback()) 
 
// 設(shè)置監(jiān)聽(tīng)端口 
httpServer.listen(port, hostname, () => { 
 console.log(`app is running at port:${port}`) 
 console.log(`url: http://${hostname}:${port}`) 
 cp.exec(`explorer http://${hostname}:${port}`, () => {}) 
}) 

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

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

Node.js原生api搭建web服務(wù)器的方法步驟:node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.j
推薦度:
標(biāo)簽: 過(guò)程 API 搭建
  • 熱門焦點(diǎn)

最新推薦

猜你喜歡

熱門推薦

專題
Top
主站蜘蛛池模板: 亚洲成色999久久网站 | 欧美 日韩 国产在线 | 欧美系列在线 | 狠狠色狠狠色合久久伊人 | 国产观看| 亚洲一区二区免费视频 | 成人a免费视频播放 | 欧美91精品久久久久网免费 | 亚洲精品美女久久久aaa | 一区二区三区成人 | 亚洲第一页在线视频 | 国产伦精品一区二区三区高清 | 日韩视频免费在线观看 | 久久首页 | 日韩 国产 欧美 精品 在线 | 欧美亚洲综合网 | 午夜精品一区二区三区在线观看 | 国产一区二区日韩欧美在线 | 日韩欧美一区二区三区久久 | 亚洲精品影院久久久久久 | 欧美日韩国 | 欧美日韩极品 | 午夜视频一区 | 另类欧美日韩 | 久久无码精品一区二区三区 | 久久国产精品免费一区二区三区 | 成人精品久久 | 久久精品国产亚洲a不卡 | 成人免费久久精品国产片久久影院 | 欧美黄色第一页 | 精品一区二区三区在线观看 | 久久久久久综合一区中文字幕 | 成人一区二区免费中文字幕 | 亚洲欧美国产精品 | 精品一区 二区三区免费毛片 | 欧美区一区 | 欧美一区二区在线观看 | 亚洲伊人精品 | 久久精品1 | 国产高清一区二区三区视频 | 国产又大又粗又猛又爽的视频 |