最近新的项目使用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 });
原文:https://www.cnblogs.com/chenzehua/p/11024981.html