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>由于

猜你喜欢

转载自www.cnblogs.com/axu1997/p/12289657.html