最近新的項目使用vue,開啟 vue history 模式打包后發現無法正常打開,網上搜索的方法千篇一律全是開發模式下的。
有道是自己動手豐衣足食,用簡單的node實現代理支持vue history,以供身為前端菜鳥的本萌新檢查自己的生產模式打包的項目是否正常。
廢話不多說,下面貼代碼:
1 // 尊重作者,注明出處。 2 // https://www.cnblogs.com/chenzehua/p/11024981.html 3 // https://github.com/r0o0en 4 var http=require('http'), 5 url=require('url'), 6 fs=require('fs'), 7 path=require('path'); 8 const httpPort = 8090; 9 10 function onRequest (request,response) { 11 //獲取請求的決定路徑。(dirname:目錄名稱) 12 var pathname = __dirname + url.parse(request.url).pathname; 13 console.log("原始請求路徑: " + pathname); 14 //設置跨域白名單 15 response.setHeader('Access-Control-Allow-Origin','http://192.168.1.176'); 16 17 //如果 最后面為 '/index','/about' 之類,則在后面加上'.html'后綴。 18 if( url.parse(request.url).pathname!='/' && !(/[\.]\D+$/ig.test(path.basename(pathname))) ){ 19 // pathname += '.html'; 20 pathname = "index.html"; 21 } 22 //如果請求路徑最后面為'/'或者連'/'都沒有,就要加上默認值'/index.html',使用path模塊 23 if (pathname.charAt(pathname.length-1)=="/"){ 24 // pathname+="index.html"; 25 pathname = "index.html"; 26 } 27 console.log("處理后請求路徑: " + pathname); 28 fs.stat(pathname,function(error,stats) { 29 if(!error && stats.isFile()){ 30 switch(path.extname(pathname)){ 31 case ".html": 32 response.writeHead(200, {"Content-Type": "text/html;charset=utf-8;"}); 33 break; 34 case ".js": 35 response.writeHead(200, {"Content-Type": "text/javascript"}); 36 break; 37 case ".css": 38 response.writeHead(200, {"Content-Type": "text/css"}); 39 break; 40 case ".json": 41 response.writeHead(200, {"Content-Type": "text/json"}); 42 break; 43 case ".gif": 44 response.writeHead(200, {"Content-Type": "image/gif"}); 45 break; 46 case ".jpg": 47 response.writeHead(200, {"Content-Type": "image/jpeg"}); 48 break; 49 case ".png": 50 response.writeHead(200, {"Content-Type": "image/png"}); 51 break; 52 default: 53 response.writeHead(200, {"Content-Type": "application/octet-stream"}); 54 }; 55 fs.readFile(pathname,function (err,data){ 56 response.end(data); 57 }); 58 }else{ 59 response.writeHead(200,{'Content-Type':'text-plain;charset="utf-8";'}); 60 response.end("<p>404 找到的你請求的資源!</p>"); 61 } 62 }) 63 } 64 console.log('開啟服務器'); 65 http.createServer(onRequest).listen(httpPort,() => { 66 console.log('Server listening on: http://localhost:%s', httpPort) 67 });