node.js - nodejs引入webpack打包后的項(xiàng)目里的index.html,把html格式識別成js??
問題描述
webpack把js等文件打包到/dist/build.js里,我在index.html里引入這個(gè)js。直接這樣點(diǎn)擊index.html,是有效果出來的。說明打包過程沒出錯(cuò)。
現(xiàn)在我用nodejs構(gòu)建服務(wù)端,當(dāng)我把這個(gè)index.html文件sendFile過去,報(bào)錯(cuò),把index.html認(rèn)成build.js??
錯(cuò)誤信息
index.js代碼
const express = require(’express’)const app = express();app.get(’*’,function(req, res) { res.sendFile(’index.html’,{root:__dirname+'/../'},function(err) {if(err) { console.log(err)}else { console.log(’yes’);} });})app.listen(3000,function() { console.log(’example app listening at 3000’);})
而且,我localhost:3000/的時(shí)候,發(fā)現(xiàn)控制臺輸出了三個(gè)yes。。。為啥的???執(zhí)行了3次???
問題解答
回答1:第一次請求,index.html第二次請求,favicon圖標(biāo)第三次請求,bundle.js文件
但是你寫的路由只要有訪問就返回index.html所以,第三次訪問時(shí),想要一個(gè)js文件,就把你返回的html文件當(dāng)js啦
建議使用static中間件來解決靜態(tài)文件訪問,或者分別寫路由
