node.js - nodejs引入webpack打包后的項目里的index.html,把html格式識別成js??
問題描述
webpack把js等文件打包到/dist/build.js里,我在index.html里引入這個js。直接這樣點擊index.html,是有效果出來的。說明打包過程沒出錯。
現在我用nodejs構建服務端,當我把這個index.html文件sendFile過去,報錯,把index.html認成build.js??
錯誤信息
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/的時候,發現控制臺輸出了三個yes。。。為啥的???執行了3次???
問題解答
回答1:第一次請求,index.html第二次請求,favicon圖標第三次請求,bundle.js文件
但是你寫的路由只要有訪問就返回index.html所以,第三次訪問時,想要一個js文件,就把你返回的html文件當js啦
建議使用static中間件來解決靜態文件訪問,或者分別寫路由
