vue本地打开build后生成的dist文件夹index.html问题
1.问题描述:
npmrunbuild在dist文件生成了index和static文件夹,为什么本地打开不了,给后端就能打开?
如何才能像访问npmrundev的地址那样访问?
2.种简单方法
2.1修改配置在本地访问
更改一些路径参数后,然后再次运行npmrunbuild就可以在本地打开index.html
改哪里?
config/index.js文件
build:{ assetsPublicPath:'/' }
改成
build:{ assetsPublicPath:'./' }
修改后再次运行npmrunbuild
双击index.html即可
2.2通过在dist目录中起服务访问
step1:
在dist文件中添加server.js
varexpress=require('express'); varapp=express(); consthostname='localhost'; constport=8080; app.use(express.static('./')); app.listen(port,hostname,()=>{ console.log(`Serverrunningathttp://${hostname}:${port}`); });
step2:
在dist路径下,npminstallexpress
step3:
nodeserver
3.其他:
3.1本地访问不足
如果ajax请求的数据是通过访问本地文件伪造的,那么会报跨域错误
不支持跨域读取本地data
本地访问路径如:
file:///Users/Downloads/vue-travel-master/dist/index.html
3.2生产环境不支持proxyTable
config/index.js中,只有开发环境dev中配置了proxyTable,支持访问代理路径
但是在build中配置无效,不支持代理地址
比如我在开发环境中请求数据
axios.get('/api/index.json?city='+this.city)
开发环境的proxyTable:
proxyTable:{ '/api':{ target:'http://localhost:8080', changeOrigin:true,//允许跨域 pathRewrite:{ '^/api':'/static/mock' } }
访问路径会替换成 http://localhost:8080/static/mock/index.json
但是生产环境不支持这样,路径要写全:
axios.get('/static/mock/index.json?city='+this.city)
这样在dist目录下nodeserver就可以访问了和npmrundev的效果是一模一样的!
起服务访问地址:
http://localhost:8080/static/js/app.5115f466b0f6ef56da51.js
3.3express配置
varexpress=require('express'); varapp=express(); consthostname='localhost'; constport=8080;
//Express提供了内置的中间件express.static来设置静态文件 app.use(express.static('./')); app.listen(port,hostname,()=>{ console.log(`Serverrunningathttp://${hostname}:${port}`); }); express.static('./')
express会在静态资源目录下查找文件,即server.js的上层路径dist目录,现在你可以加载dist目录下的文件了,如:
http://localhost:8080/static/mock/index.json?city=%E4%B8%8A%E6%B5%B7
访问路径为:
——dist ——static ——css ——js ——mock ——a.json ——index.html ——server.js
4.代码
4.1可运行代码链接
可下载运行试试
总结
以上所述是小编给大家介绍的vue本地打开build后生成的dist文件夹index.html问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!