Node.js原生api搭建web服务器的方法步骤

2020-06-17 05:58:38易采站长站整理

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}`, () => {})
})