nodejs使用express中靜態資源托管(express.static())時遇到的bug


如下:將test.html的頁面掛載在服務器上,

const express= require('express') 
const fs= require('fs') 
let app = express();
// app.use(express.static('node_modules'))
app.use(express.static('node_modules'))
app.listen('4000',()=>{
    console.log("http://127.0.0.1:4000")
})
app.get('/',(req,res)=>{
    fs.readFile('./test.html','utf-8',(err,data)=>{
        console.log(data)
        res.end(data)
    })
})

test.html如下,頁面為一個wangEditor的demo,jq資源在本地引入

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
</head>
<body>
    <div id="editor">
        <p></p>
    </div>
    <button class="getsomething">獲取</button>
    <!-- 注意, 只需要引用 JS,無需引用任何 CSS !!!-->
    <script src="https://cdn.bootcss.com/wangEditor/10.0.13/wangEditor.js"></script>
     <script src="./node_modules/jquery/dist/jquery.js"></script>
    <script type="text/javascript">
        var E = window.wangEditor
        var editor = new E('#editor')
        // 或者 var editor = new E( document.getElementById('editor') )
        editor.create()
        let getsomething = document.querySelector('.getsomething');
        getsomething.onclick= function(){
            $.get({
                url:'http://127.0.0.1:4040/setids'
            })
            console.log(editor.txt.html())
        }
    </script>
</body>
</html>

此時已經設置了靜態資源托管,但是調用http://127.0.0.1:4000時會報錯,錯誤為找不到jq資源,如下

此時bug的原因為jq的引入問題(test.html中14行代碼)

<script src="./node_modules/jquery/dist/jquery.js"></script>由於

解決方法

法一

由於設置了靜態資源托管(app.use(express.static('node_modules')))因此在html中調用資源的時候不需要加上./node_modules,即如下引入即可

<script src="./jquery/dist/jquery.js"></script>

法二

或者為其設置一個虛擬路徑,在靜態資源管理時使用如下代碼

app.use('/node_modules',express.static('node_modules'))

ps:若使用aaa為虛擬路徑則修改如下
js文件

app.use('/aaa',express.static('node_modules'))

html中引用

<script src="./aaa/jquery/dist/jquery.js"></script>由於


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM