zoukankan      html  css  js  c++  java
  • 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>由于
  • 相关阅读:
    角色扮演游戏引擎的设计原理
    游戏服务器架构
    小谈网络游戏同步
    What is the single most influential book every programmer should read?
    Research Scientists and Engineers
    关于为什么不推荐使用用户定义表类型的说明
    程序员必须遵守的编程原则
    CacheStrategy缓存
    正能量
    MEF 和 MAF
  • 原文地址:https://www.cnblogs.com/axu1997/p/12289657.html
Copyright © 2011-2022 走看看