最近新的项目使用vue,开启 vue history 模式打包后发现无法正常打开,网上搜索的方法千篇一律全是开发模式下的。
有道是自己动手丰衣足食,用简单的node实现代理支持vue history,以供身为前端菜鸟的本萌新检查自己的生产模式打包的项目是否正常。
废话不多说,下面贴代码:
// https://www.cnblogs.com/chenzehua/p/11024981.html
// https://github.com/r0o0en
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const os = require('os');
const httpPort = 8889
function onRequest (request, response) {
console.log('———— start ——————————')
const myURL = url.parse(request.url)
// 获取请求的决定路径。(dirname:目录名称)
let pathname = path.join(__dirname,myURL.pathname)
console.log(`原始请求路径: ${pathname}`)
// 设置跨域白名单
response.setHeader('Access-Control-Allow-Origin', '*')
if (myURL.pathname === '/') {
// 如果请求路径最后面为'/'或者连'/'都没有,就要加上默认值'/index.html',使用path模块
pathname = path.join('index.html')
} else if (!(/[.]\D+$/ig.test(path.basename(pathname)))) {
// 如果 最后面为 '/index','/about' 之类,则在后面加上'.html'后缀。
pathname = path.join('index.html')
}
console.log(`处理后的路径: ${pathname}`)
fs.stat(pathname, (error, stats) => {
if (!error && stats.isFile()) {
switch (path.extname(pathname)) {
case '.html':
response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8;' })
break
case '.js':
response.writeHead(200, { 'Content-Type': 'text/javascript' })
break
case '.css':
response.writeHead(200, { 'Content-Type': 'text/css' })
break
case '.json':
response.writeHead(200, { 'Content-Type': 'text/json' })
break
case '.gif':
response.writeHead(200, { 'Content-Type': 'image/gif' })
break
case '.jpg':
response.writeHead(200, { 'Content-Type': 'image/jpeg' })
break
case '.png':
response.writeHead(200, { 'Content-Type': 'image/png' })
break
default:
response.writeHead(200, { 'Content-Type': 'application/octet-stream' })
}
fs.readFile(pathname, (err, data) => {
response.end(data)
})
} else {
response.writeHead(200, { 'Content-Type': 'text-plain;charset="utf-8";' })
response.end('<p>404 找到的你请求的资源!</p>')
}
})
}
function getIPAdress() {
let interfaces = os.networkInterfaces();
console.log('interfaces',interfaces);
for (let devName in interfaces) {
let iface = interfaces[devName];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
return alias.address;
}
}
}
}
http.createServer(onRequest).listen(httpPort, () => {
const myIp = getIPAdress();
console.log('Server listening on: http://localhost:%s', httpPort);
console.log('Server listening on: http://%s', myIp +':'+ httpPort);
})