通过node服务器实现支持 vue history 模式
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了通过node服务器实现支持 vue history 模式,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3015字,纯文字阅读大概需要5分钟。
内容图文
![通过node服务器实现支持 vue history 模式](/upload/InfoBanner/zyjiaocheng/801/44d91e9522f1475fbb726106d3f983dc.jpg)
最近新的项目使用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 });
内容总结
以上是互联网集市为您收集整理的通过node服务器实现支持 vue history 模式全部内容,希望文章能够帮你解决通过node服务器实现支持 vue history 模式所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。