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

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

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