npm run build 在dist 文件生成了 index 和 static 文件夾,爲何本地打開不了,給後端就能打開?css
如何才能像訪問 npm run dev 的地址那樣訪問?html
更改一些路徑參數後,而後再次運行npm run build 就能夠在本地打開index.html 改哪裏? config/index.js文件 build: { assetsPublicPath: '/' } 改爲 build: { assetsPublicPath: './' } 修改後再次運行 npm run build 雙擊 index.html 便可
step1:vue
在dist 文件中添加 server.js
var express = require('express'); var app = express(); const hostname = 'localhost'; const port = 8080; app.use(express.static('./')); app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}`); });
step 2:node
在dist 路徑下,npm install express
step 3:ios
node server
若是ajax請求的數據是經過訪問本地文件僞造的,那麼會報跨域錯誤git
不支持跨域讀取本地datagithub
本地訪問路徑如:ajax
file:///Users/Downloads/vue-travel-master/dist/index.html
config/index.js 中,只有開發環境dev中配置了proxyTable,支持訪問代理路徑
可是在 build 中配置無效,不支持代理地址express
好比我在開發環境中請求數據npm
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目錄下 node server 就能夠訪問了 和 npm run dev 的效果是如出一轍的! 起服務訪問地址: http://localhost:8080/static/js/app.5115f466b0f6ef56da51.js
var express = require('express'); var app = express(); const hostname = 'localhost'; const port = 8080; //Express 提供了內置的中間件 express.static 來設置靜態文件 app.use(express.static('./')); app.listen(port, hostname, () => { console.log(`Server running at http://${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